Jonh
Jonh

Reputation: 95

How to perform deep populate mongoose?

this is my question.js and user.js schema model with mongoose as below, could anyone help how to populate all the username lists in array object of likes:[] with Node js because I was facing this problem almost 2 weeks now, I could not populate the username from a user inside likes. Please, I appreciate your suggestion.

question schema model

user schema model

Upvotes: 0

Views: 404

Answers (3)

Vishnu8429
Vishnu8429

Reputation: 104

To populate user details, Please use

Post.findOne( { _id: id } )
    .populate( "user" )
    .populate( "likes.user" );

To get liked post, please use

Post.find({ "likes": { "$gt": 0 } }, function(err, data) {
})

or using where, here may get error if likes fields is missing or empty, so please check if it is exists

Post.find( {$where:'this.likes.length>0'} )

so please use where and exists

Post.find( {likes: {$exists:true}, $where:'this.likes.length>0'} )

Upvotes: 1

Jonh
Jonh

Reputation: 95

Yes, thank you to Ratnadeep Bhattacharyya, now I able to populate username in likes array object and also able to return the only a specific array of likes. Below is the working code: Happy Coding, Jonh

//@route api/post/get/likes
router.get('/get/likes/:postId', auth, async (req, res) => {
  try {
    //check if post exist
    const likes = await Post.findOne({ _id: req.params.postId })
      .populate('user', ['name'])
      .populate('likes.user', ['name']);
    return res.status(200).json(likes.likes);
  } catch (error) {
    console.log(error.message);
    res.status(500).json({ msg: 'Server error' });
  }
});

Upvotes: 0

I tried your code and got it working using your model. If you are using user only you can directly call .populate("user") but if its nested you need to do .populate("likes.user")

Post.findOne( { _id: id } ).populate( "user" ).populate( "likes.user" );

Upvotes: 1

Related Questions