I'm having a problem with a callback mess.
In my nodejs app, I'm trying to get an array of JSON Objects returned by a mongoDB request. I don't know why, but it don't populate as I want.
I suspect a problem of asynchronous results/callback mess.
var fruits = ["Peach", "Banana", "Strawberry"];
var finalTab = [];
fruits.forEach(function(fruit) {
db.collection('mycollection').distinct("column1", {"column2":{$regex :fruit}}, (function(err, result) {
finalTab[fruit] = result;
console.log(result); // -> display the desired content
db.close();
if (err) throw err;
}));
});
console.log(finalTab); // -> []
Thanks by advance for help.
EDIT : As I need all results returned by my db.collection...functions... I'm trying to add these async commands to a queue, execute it and get a callback function. I think that async nodejs module can help.
Can someone tell me how to do this in a ForEach() ?