猫鼬填充 - 何时

Mongoose populate - when

我想用作者姓名填充 posts。我创建了带有参考和路线的模型。我什么时候应该填充 posts,在保存新的 post 之前或之后,它实际上是如何工作的?

填充用于查询将一个文档中存储的 id 替换为另一个集合中的相应文档。

您需要将作者文档的 _id 保存在您的 post 文档中:

var post = new Post({
  ...
  author: // id of author doc
  ...
})

post.save()

然后您将在检索文档时使用 populate,以便将存储的作者 ID 替换为作者文档本身:

Post
  .find({})
  .populate('author')
  .exec(function (err, posts) {
    if (err) {
      // Handle error
    }

    // Handle results
    posts.forEach(post => {
      // Assuming author documents have a 'name' property
      console.log(post.author.name)
    })
  })

这也可能有帮助: http://mongoosejs.com/docs/populate.html