填充已获取的文档。有可能吗?如果可以,怎么办?

Populating on an already fetched document. Is it possible and if so, how?

我有一个文档提取为:

Document
  .find(<condition>)
  .exec()
  .then(function (fetchedDocument) {
    console.log(fetchedDocument);
  });

现在此文档引用了另一个文档。但是当我查询这个文档时,我没有填充那个引用。相反,我想稍后填充它。那么有没有办法做到这一点?我可以这样做吗:

fetchedDocument
  .populate('field')
  .exec()
  .then(function (reFetchedDocument) {
    console.log(reFetchedDocument);
  });

我遇到的另一种方法是这样做:

Document
  .find(fetchedDocument)
  .populate('field')
  .then(function (reFetchedDocument) {
    console.log(reFetchedDocument);
  });

现在是重新重新获取整个文档还是只获取填充的部分并将其添加进去?

你的第二个例子(Document.find(fetchedDocument))效率很低。它不仅从 MongoDB 重新获取整个文档,它还使用以前获取的文档的所有字段来匹配 MongoDB 集合(不仅仅是 _id 字段)。因此,如果您的文档的某些部分在两次请求之间发生了变化,此代码将找不到您的文档。

你的第一个例子(fetchedDocument.populate)很好,除了 .exec() 部分。

Document#populate method returns a Document, not a Query, so there is not .exec() method. You should use special .execPopulate() method 改为:

fetchedDocument
  .populate('field')
  .execPopulate()
  .then(function (reFetchedDocument) {
    console.log(reFetchedDocument);
  });