admin管理员组

文章数量:1333211

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

本文标签: javascriptPopulating on an already fetched document Is it possible and if sohowStack Overflow