2

I'm trying to put data into an object. Although this object in loop has value, this object out of the loop hasn't value (empty). I had instance object global variable obj. What's wrong with me?

p.s : findOne is a mongoose's method. (mongodb).

var obj = [];
for(var i = 0;i<anotherObj.length;i++){
    var id = anotherObj[i].id;
    model.findOne({_id:id},function(err,user){
        if(!err){
            obj.push(user);
            console.log(obj); /* <= it has value */
        }
    })
}

      console.log(obj);  /* <= this is null */
Loint
  • 3,560
  • 7
  • 26
  • 46
  • 1
    Because the bottom one gets executed before the loop and callback function return the object. So, it's empty (or null) until then. – Jeremy Jackson Jun 15 '16 at 18:57
  • 1
    You are running into asynchronous issues here. Your `console.log` on the final line is being evaluated before your mongoose method finishes running. Look into callbacks and/or promises. – dYale Jun 15 '16 at 18:58

2 Answers2

1

Your findOne callback runs asynchronous, meaning that your last console.log runs before you push the user to the obj (array).

You would need to call a function after every user in the loop has been fetched. Try the async package

tbleckert
  • 3,763
  • 4
  • 32
  • 39
  • I tried to async package module and I have an issue. Should I update my post or comment dirrecty on this answer?. – Loint Jun 15 '16 at 20:22
1

Your query to mongoose are asynchronous. The callbacks will be executed only on the next iteration of the event loop/when the data is available. That is why you see the obj being null.

ffff
  • 2,853
  • 1
  • 25
  • 44