![](/img/trans.png)
[英]How to perform FIND, then perform AND, then perform OR with POPULATE in Mongoose
[英]How to perform deep populate mongoose?
我尝试了您的代码并使用您的模型使其正常工作。 如果你只使用user
你可以直接调用.populate("user")
但如果它嵌套你需要做.populate("likes.user")
Post.findOne( { _id: id } ).populate( "user" ).populate( "likes.user" );
要填充用户详细信息,请使用
Post.findOne( { _id: id } )
.populate( "user" )
.populate( "likes.user" );
要获得喜欢的帖子,请使用
Post.find({ "likes": { "$gt": 0 } }, function(err, data) {
})
或使用 where,如果喜欢字段缺失或为空,这里可能会出错,所以请检查它是否存在
Post.find( {$where:'this.likes.length>0'} )
所以请使用 where 和 exists
Post.find( {likes: {$exists:true}, $where:'this.likes.length>0'} )
是的,感谢 Ratnadeep Bhattacharyya,现在我能够在喜欢数组对象中填充用户名,并且还能够返回唯一的特定喜欢数组。 以下是工作代码: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.