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

Sci*_*tes 2 javascript mongoose node.js

我有一个文件提取为:

Document
  .find(<condition>)
  .exec()
  .then(function (fetchedDocument) {
    console.log(fetchedDocument);
  });
Run Code Online (Sandbox Code Playgroud)

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

fetchedDocument
  .populate('field')
  .exec()
  .then(function (reFetchedDocument) {
    console.log(reFetchedDocument);
  });
Run Code Online (Sandbox Code Playgroud)

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

Document
  .find(fetchedDocument)
  .populate('field')
  .then(function (reFetchedDocument) {
    console.log(reFetchedDocument);
  });
Run Code Online (Sandbox Code Playgroud)

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

Leo*_*tny 7

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

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

Document#populate方法返回a Document,而不是a Query,所以没有.exec()方法.您应该使用特殊.execPopulate()方法:

fetchedDocument
  .populate('field')
  .execPopulate()
  .then(function (reFetchedDocument) {
    console.log(reFetchedDocument);
  });
Run Code Online (Sandbox Code Playgroud)