1

doing a mongo DB lookup, intending to save result in a scoped variable.

var users = ['kat'];

collection.find({key: key}, function(err, doc) {
    if (doc) {
        var firstEntry = doc[0];
        users = firstEntry.users;
        users.push('jack');
    } else {
        console.log("DB ERROR: cannot find: " + key);
    } 
});

console.log(users); // Why does this return only Kat, and Jack is not appended? 

Thanks!

kaid
  • 1,249
  • 2
  • 16
  • 32

1 Answers1

1

you can't predict when the callback function is going to execute.. thats why user's array is not updated properly.. When the callback fires the array will update itself but until it does, the array will be the same. The callback function will only execute when the find event completes, but that doesn't mean it will block the execution of the rest of the code.. callback fire asynchronously. Hope that helps! at least hints in the correct direction :)

Handle the success logic(console.log) inside the callback..

Lakmal Caldera
  • 1,001
  • 2
  • 12
  • 25