最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin5浏览0评论

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论