0
我想通過使用貓鼬「findOne」在for循環中從我的MongoDB中獲得結果,然後將結果推送到數組中。找到的結果總是正確的,但它不會將其推入我的數組中,它始終保持爲空。我試着承諾,所以使用後,findOne像貓鼬推結果到數組
Company.findOne().exec(...).then(function(val){
//here comes then the push function
});
但也返回一個空的數組。現在我的代碼如下所示:
var Company = require('../app/models/company');
function findAllComps(){
var complist = [];
for (var i = 0, l = req.user.companies.length; i < l; i++) {
var compid = req.user.companies[i];
Company.findOne({id: compid}, function(err, company){
if(err)
return console.log(err);
if (company !== null)
//result is an object
complist.push(company);
});
}
return complist;
}
res.json(findAllComps());
我感謝所有幫助:)
使用'async'或'promises' –
它應該是什麼樣子?正如我所說我在執行後用「then」試過了,但那也沒有奏效 –