I am using the listCollection method in mongodb and looping through each returned collection with a query using find.
The problem is that I use the loop to construct an object that I wish to return with response.json after the loop is done but since find is async I am stuck at figuring how to "wait" until every find callback has finished before returning response.json()
var data = {};
database.listCollections({name: {$ne: 'system.indexes'}}).toArray(function(err, collections) {
if (err) return res.json({});
for(i=0; i<collections.length; i++){
var collection = collections[i].name;
database.collection(collection).find(query, limit)
.sort({"Date": -1}).toArray(function(err, docs){
if (err) return res.json({
});
/* Do stuff with docs, push stuff to data */
});
/** Console shows blank **/
console.log("Data " + i+ ": " + JSON.stringify(data));
}
/** Response is blank.. **/
res.json(data);
});
The problem is that the for loop returns way before the find()s are done. How do I deal with this in a JS/Node way? I can hack together a solution but I might encounter a similar problem later..
Edit: I am certain that data is actually returned and processed properly, as a console.log() inside each find on data shows that it actually has content.