我试图通过使用mongoose“findOne”从for循环中获取MongoDB的结果,然后将结果推送到数组中。找到的结果总是正确的,但它不会将它推入我的数组,它一直保持为空。我用promises尝试过,所以在findOne之后使用a
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());
我感谢任何帮助:)
答案 0 :(得分:2)
如果req.user.companies
是一系列ID,您只需使用$in
operator查找具有任何ID的所有公司。
// find all companies with the IDs given
Company.find({ id: { $in: req.user.companies }}, function (err, companies) {
if (err) return console.log(err);
// note: you must wait till the callback is called to send back your response
res.json({ companies: companies });
});