Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

200
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

Post.findOne({ _id: req.params.postId }).populate([
  { 
    path: 'comments', 
    populate: [{ path: 'user' }] 
  }
]);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!