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”试过了,但那也没有奏效 –