0

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 Answer 1

2

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);
});
Sign up to request clarification or add additional context in comments.

2 Comments

But it doesn't work as espected :/ Here's the output : [] // and empty tab (finalTab) [ '1', '01', '001'] // output of result under the db.collection function [ '123456', '123' ] // output of result under the db.collection function [ '123456' ] // output of result under the db.collection function
I finally got it working. Thanks a lot man ! You made my day :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.