正在对已提取的文档进行填充.有可能吗?如果有,怎么做

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

本文关键字:如果 有可能 填充 提取 文档      更新时间:2023-09-26

我有一个文档被提取为:

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方法返回Document,而不是Query,因此不存在.exec()方法。您应该使用特殊的.execPopulate()方法:

fetchedDocument
  .populate('field')
  .execPopulate()
  .then(function (reFetchedDocument) {
    console.log(reFetchedDocument);
  });
相关文章: