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

I have a document fetched as:Document.find(<condition>).exec().then(function (fetchedDocument) {c

I have a document fetched as:

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

Now this document has a reference to another document. But I am not populating that reference when I'm querying this document. Instead, I wanna populate it later. So is there any way of doing that? Can I do this:

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

Another method I came across is to do this:

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

Now does this re-fetch the entire document all over again or just fetch the populated part and add it in?

I have a document fetched as:

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

Now this document has a reference to another document. But I am not populating that reference when I'm querying this document. Instead, I wanna populate it later. So is there any way of doing that? Can I do this:

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

Another method I came across is to do this:

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

Now does this re-fetch the entire document all over again or just fetch the populated part and add it in?

Share Improve this question asked Apr 3, 2015 at 10:35 BadgerBadgerBadgerBadgerBadgerBadgerBadgerBadger 3744 silver badges19 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

Your second example (with Document.find(fetchedDocument)) is highly inefficient. It's not only re-fetching the whole document from MongoDB, it's also uses all fields of previously fetched document to match against MongoDB collection (not just _id field). So, if some part of your document changed between two requests, this code won't find your document.

Your first example (with fetchedDocument.populate) is fine, except for .exec() part.

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

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742276563a4413699.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信