Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I populate a reference within a reference with Mongoose and MongoDB

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading