returning JSON Array in Node

Im still trying to get my head around the asynchronous flow in Node. Im trying to read list of files in db and convert result to json array and return back. The code works fine for one json object. But there is no output when reading the complete array

So this is the code

Function call - receive ajax request from browser and send back result

module.retrieveSourceContent(req, res, result, function(err, result){
                if(err){
                  console.log(err);
                  return;
                }
                console.log(result);
                res.contentType('json');
                res.write(JSON.stringify(result));
                res.end();
            });

Code

 retrieveSourceContent : function(req, res, sourceList, callback){
        var sourceContent = new Array();
        MongoClient.connect(config.mongoPath+config.dbName, function(err, db) {
           if(err){
             return callback(new Error("Unable to Connect to DB"));
           }
           var collection = db.collection(config.source);
           for( i=0;i<sourceList['sources_FOR'].length;i++){
              //build the source JSON Array
              collection.find({'_id':sourceList['sources_FOR'][i]}).nextObject(function(err, doc) {
                if(err)
                  return callback(new Error("Error finding data in DB"));
                    var sourceObject = {
                        title     :doc.name,
                        tagCount  :doc.tag.length,
                        tags      :doc.tag,       
                        format    :doc.type,     // Differentiate text, image, video and urls
                        content   :doc.data      // Content
                    };
                    sourceContent.push(sourceObject);
                    //if(i == sourceList['sources_FOR'].length - 1)
                      return callback(null, sourceContent);

              });
           }
        });
      }

This code return one json object to client. If i uncomment if(i == sourceList['sources_FOR'].length - 1) i have no output and no error. But sourceContent.push(sourceObject); does create the json array successfully.

Since this flow works on other language, i suspect it has something to do with asyn flow of node. Im at a loss here on how to solve this.

Any help would be great..

It's a little bit difficult following the flow of the program due to the formatting. But I think you are correct assuming that this has to do with async behaviour. If I'm not fooled by the formatting, it looks to me like you're doing the callback in every iteration of the loop, which would only work for the first iteration. I'm not sure what your sourcesList is, but I would try to construct a query that includes all the items in sourcesList. Then you would not need the foor loop. Maybe you can use the $in operator.