[英]How can I populate a reference within a reference with Mongoose and MongoDB
我有包含评论参考的帖子,评论有用户参考。 我想创建一种方法,让用户发表评论。
Post: [comment_id, comment_id]
Comment: [user_id]
以下是我到目前为止所拥有的:
postRouter.get('/:postId/comments', (req, res, next) => {
Post.findOne({ _id: req.params.postId })
.populate('comments')
// this does not work
.populate('comments.user')
.exec((err, comments) => {
if (err) {
res.status(500);
return next(err);
}
return res.status(200).send(comments);
// returns
// {
// "_id": "1234567",
// "comments": [ { "_id": "891011", "body": "hello world", "user": "456789" }]
// }
});
});
如前所述,我在哪里获得“用户”,我想用用户文档填充它。 这可能吗?
是的,这是可能的。 你可以这样做:
Post.findOne({ _id: req.params.postId }).populate([
{
path: 'comments',
populate: [{ path: 'user' }]
}
]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.