简体   繁体   English

如何执行人口密集的猫鼬?

[英]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.这是我的 question.js 和 user.js 模式模型,带有 mongoose,如下所示,任何人都可以帮助如何使用 Node js 填充 likes:[] 数组对象中的所有用户名列表,因为我现在面临这个问题将近 2 周了,我无法从喜欢的用户填充用户名。 Please, I appreciate your suggestion.拜托,我很感激你的建议。

question schema model问题模式模型

user schema model用户模式模型

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")如果你只使用user你可以直接调用.populate("user")但如果它嵌套你需要做.populate("likes.user")

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

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或使用 where,如果喜欢字段缺失或为空,这里可能会出错,所以请检查它是否存在

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

so please use where and exists所以请使用 where 和 exists

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

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.是的,感谢 Ratnadeep Bhattacharyya,现在我能够在喜欢数组对象中填充用户名,并且还能够返回唯一的特定喜欢数组。 Below is the working code: Happy Coding, Jonh以下是工作代码: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' });
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM