填充已经获取的文档。是否可能,如果可能,怎么样?

时间:2015-04-03 10:35:22

标签: javascript node.js mongoose

我将文档提取为:

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);
  });

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

1 个答案:

答案 0 :(得分:7)

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

您的第一个示例(使用fetchedDocument.populate)很好,但.exec()部分除外。

Document#populate method返回Document,而不是Query,因此没有.exec()方法。您应该使用特殊.execPopulate() method代替:

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