Manipulating a list inside of a mongodb query

First question here so hopefully I do this right...

The jest of what I'm trying to do is add to a list inside of a query and then be able to pass this list on to my client from node.js. My code (simplified) is as follows:

socket.on('get_new', function() {   
var db = require('mongojs').connect('test', ['col1']);
var db2 = require('mongojs').connect('test', ['col2']);

db.col1.find( function(err, tups) {

    var total = [];

    if ( err || !rows ) { console.log("error") };
    else { 

          for(row in tups){ 
               var id = row['id'];

               db2.col2.find({name:id}, function(foo, bar){

                  if ( foo || !bar ) { console.log("error") }; 
                  else {

                     total += { name : bar['age'] };
                     console.log(total); //prints [ {alex:'20'}]
                  }
               }
           }
    }

  console.log(total); // prints []

}
}

As I showed in the code, I have put some console.log statements to see the value and it is different inside of the query vs after. I'm guessing it has something to do with the scope of this code, it seems to me as if after db.test2.find is run, what happened inside doesn't exist outside, but I don't get why. Thanks in advance!

The code is asynchronous. What this means in practice is that your last statement: console.log(total); is executed before the first. To print the actual total you'd want to do wrap that code in a function like this:

function myFnForTotal(notifyTotal) {

/* your code above the else  */
 total += someTotal;
 console.log(total); //prints [ {alex:'20'}]
 notifyTotal(total);
/* your code below else */
}

myFnForTotal(function(total) {
  console.log(total);
});