2015-04-03 55 views
2

我要取的文件爲:填充已獲取的文檔。這是可能的,如果是這樣,怎麼樣?

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

現在,這是否再取出整個文檔一遍還是隻取人口稠密的部分,並將其添加在?

回答

6

你的第二個例子(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); 
    }); 
+0

好了,所以'fetchedDocument.populate( '田')的exec(),然後(函數(reFetchedDocument){ 的console.log(reFetchedDocument); });'。將工作? – ScionOfBytes 2015-04-03 12:48:27

+1

是的,它應該工作,除了'.exec()'部分。 ['Document#populate'方法](http://mongoosejs.com/docs/api.html#document_Document-populate)返回一個'Document',而不是'Query',所以沒有'.exec()'方法。所以你應該使用特殊的'.execPopulate()'方法。 – 2015-04-03 12:54:10

+0

@Kaylors將其添加到我的答案。 – 2015-04-03 12:59:39

相關問題