Home > Back-end >  How can I populate a reference within a reference with Mongoose and MongoDB
How can I populate a reference within a reference with Mongoose and MongoDB

Time:03-30

I have Posts which contains a comments reference, the comments have a user reference. I want to create a method in which I can get the user with their comment.

    Post: [comment_id, comment_id]
    Comment: [user_id]

The following is what I have so far:

postRouter.get('/:postId/comments', (req, res, next) => {
  Post.findOne({ _id: req.params.postId })
    .populate('comments')
      // this does not work
    .populate('comments.user')
    .exec((err, comments) => {
      if (err) {
        res.status(500);
        return next(err);
      }
      return res.status(200).send(comments);
      // returns
      // { 
      // "_id": "1234567", 
      // "comments": [ { "_id": "891011", "body": "hello world", "user": "456789" }]
      //  }
    });
});

As stated before where I get the "user" I would like to populate it with the user document. Is this possible?

CodePudding user response:

Yes, it's possible. You can do it like this:

Post.findOne({ _id: req.params.postId }).populate([
  { 
    path: 'comments', 
    populate: [{ path: 'user' }] 
  }
]);
  • Related