0

I was trying to get a result from my MongoDB in a for loop by using a mongoose "findOne" and then push the results into an array. The found result is always correct, but it doesn't pushes it into my array, it stays empty all time. I tried it with promises, so use a then after the findOne like

Company.findOne().exec(...).then(function(val){
    //here comes then the push function
});

but that also returned an empty array. Now my code looks like this:

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());

I appreciate any help :)

Oliver F.
  • 208
  • 1
  • 10

1 Answers1

2

If req.user.companies is an array of IDs, you can simply use the $in operator to find all companies having any of the IDs.

// 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 });
});
Mikey
  • 6,728
  • 4
  • 22
  • 45