![](/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.