我试图通过使用猫鼬“findOne”在 for 循环中从我的 MongoDB 中获取结果,然后将结果推送到数组中。找到的结果总是正确的,但它不会将它推入我的数组,它始终保持为空。我用承诺试过了,所以在 findOne 之后使用 then
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());
我感谢任何帮助:)
如果req.user.companies
是一组 ID,您可以简单地使用$in
运算符查找所有具有任何 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 });
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句