Search code examples
node.jsmongoose-schemamongoose-populate

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


Solution

  • 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'} )