Node.js async map over MongoDB queries

2019-08-31 09:24发布

I'm having a problem with async Node.js module. In my Node.js app, I'm trying to get an array of JSON objects returned by a MongoDB request:

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); // -> []

At the moment, I'm at this point.

I'm trying to implement the async.map to iterate through Fruits collection. https://caolan.github.io/async/docs.html#map

Can someone help? :)

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.

1条回答
啃猪蹄的小仙女
2楼-- · 2019-08-31 09:36

You can try this:

async.map(fruits , function (fruit, callback) {
    db.collection('mycollection').distinct("column1", {"column2":{$regex :fruit}}, (function(err, result) {        
        //here you are assigning value as array property         
        //finalTab[fruit] = result;
        // but you need to push the value in array
        finalTab.push(result);
        console.log(result); // -> display the desired content
        db.close();
        if (err) throw err;
        //callback once you have result
        callback();
    }));
}.bind(this), function () {
    console.log(finalTab); // finally call
}, function (err, result) {
    return Promise.reject(err);
});
查看更多
登录 后发表回答