mongoose 中的 populate 函数是做什么的?
What does the populate function in mongoose do?
阅读http://mongoosejs.com/docs/populate.html时我不明白问题所在。我不完全理解 populate
函数的作用。我从 meanjs
示例源代码中提取它:
Article.find().sort('-created').populate('user', 'displayName').exec(function (err, articles) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(articles);
}});
提前致谢。
在 Article
文档中,您正在存储用户的 userId。
现在在查询 Article
文档时,如果您想要为每篇文章获取用户,那么您可以使用填充。
现在,当您访问 articles[index].user
时,它将 return 对象而不是 ObjectId
值(_id
属性 用户)。
第二个参数定义应在 User
对象中检索哪个字段。这里是displayName
。因此它将检索 User
的 _id
和 displayName
。如果要排除 _id,可以指定“-_id displayName”
阅读http://mongoosejs.com/docs/populate.html时我不明白问题所在。我不完全理解 populate
函数的作用。我从 meanjs
示例源代码中提取它:
Article.find().sort('-created').populate('user', 'displayName').exec(function (err, articles) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(articles);
}});
提前致谢。
在 Article
文档中,您正在存储用户的 userId。
现在在查询 Article
文档时,如果您想要为每篇文章获取用户,那么您可以使用填充。
现在,当您访问 articles[index].user
时,它将 return 对象而不是 ObjectId
值(_id
属性 用户)。
第二个参数定义应在 User
对象中检索哪个字段。这里是displayName
。因此它将检索 User
的 _id
和 displayName
。如果要排除 _id,可以指定“-_id displayName”