K
K
Konstantin2021-05-27 20:12:54
Mongoose
Konstantin, 2021-05-27 20:12:54

How does map work in this case?

I have a request, I don't understand verbatim how map works in this case.
The friendId variable or function was not created by me and did not appear before
Please explain what map does

router.get("/timeline/all", async (req, res) => {
    try {
      const currentUser = await User.findById(req.body.userId); //из тела запроса берем айди юзера и ищем в модели юзера
      const userPosts = await Post.find({ userId: currentUser._id }); // из модели поста ищем айди автора поста (в каждом посте указываем userId), 
                                                                    //которые совпадаю с юзером в теле запроса
      const friendPosts = await Promise.all(
        currentUser.followings.map((friendId) => { //тут не ясно откуда взялся friendId 
          return Post.find({ userId: friendId }); 
        })
      );
      res.json(userPosts.concat(...friendPosts)) //объединяем массивы 
    } catch (err) {
      res.status(500).json(err);
    }
  });

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
WapSter, 2021-05-27
@gradk

Subscribers seem to store an id array. Map returns an array of promises that Promise.all handles. This is not efficient at all, you can use model.find({ '_id': { $in: array_ids }})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question