2017-05-04 78 views
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()); 

我感谢所有帮助:)

+0

使用'async'或'promises' –

+0

它应该是什么样子?正如我所说我在执行后用“then”试过了,但那也没有奏效 –

回答

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

完美,这对我很有用,而且非常简单,谢谢! :) –