0
router.get('/', (req, res) => {
Post.find()
    .populate("author")
    .populate("comments")
    .populate("commentedBy")
    .sort({date : -1})
    .exec()
    .then(posts => res.json(posts));
});

here i am populating the comments from the comment model and then populating the 'commentedBy' from the comment model. The last populating is not working. I am getting {commentedBy: Null, ...}

3
  • Try this .populate({ path: "comments", populate: { path: "commentedBy" }}) Commented Sep 26, 2018 at 7:43
  • Thanks. Its working Commented Sep 26, 2018 at 10:50
  • 1
    Possible duplicate of mongoose recursive populate Commented Sep 26, 2018 at 11:05

1 Answer 1

1

Made some changes in your code. In your case comments are inside commentedBy so first you populate comments then you populate commentedBy inside it.

router.get('/', (req, res) => {
Post.find()
    .populate("author")
    .populate({ path: 'comments', populate: { path: 'commentedBy' } })
    .sort({date : -1})
    .exec()
    .then(posts => res.json(posts));
});
Sign up to request clarification or add additional context in comments.

2 Comments

What will be the syntax if I want to populate two children in 2nd level, like if i want to populate comments and rating in the fourth line??
populate({ path: 'comments', populate: { path: 'commentedBy', populate: [{ path: 'comments '}, { path: 'ratings'}] } }) is this what you're asking?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.