2017-05-04 77 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

完美,這對我很有用,而且非常簡單,謝謝! :) –