Thursday, 4 May 2017

mongoose push result to array

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(){
    //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 :)



via Oliver F.

No comments:

Post a Comment