【问题标题】:What does the populate function in mongoose do?猫鼬中的填充功能有什么作用?
【发布时间】:2016-02-26 16:10:56
【问题描述】:

当我阅读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);
}});    

提前致谢。

【问题讨论】:

    标签: node.js mongodb mongoose mean meanjs


    【解决方案1】:

    Article 文档中,您正在存储用户的 userId。

    现在在查询Article 文档时,如果您希望为每个文章获取用户,那么您可以使用填充。

    现在当您访问articles[index].user 时,它将返回对象而不是ObjectId 值(用户的_id 属性)。

    第二个参数定义应该在User 对象中检索哪个字段。这里是displayName。因此它将检索User_iddisplayName。如果要排除 _id 可以指定“-_id displayName”

    【讨论】:

    • 非常感谢,它对我很有用,祝你有美好的一天:)
    猜你喜欢
    • 2020-01-16
    • 2020-01-17
    • 2018-02-12
    • 2015-05-29
    • 1970-01-01
    • 2014-12-19
    • 2020-07-25
    • 2015-07-13
    • 2016-10-10
    相关资源
    最近更新 更多