How to make for loop in node.js and mongoDB run synchronously

Viewed 2172

This is my first time with Node.js, and I'm having an issue with it.

I'm getting some data from an API, and I'm storing them on a array.

Then, I'm doing some MongoDB's query to know if the data that I have on that array are in the database.

I thought to use a for loop for every occurrence of array, but when I try to call MongoDB, for loop keep going to increase the counter immediately, without waiting the end of query and relative response, and I get data only for the last occurrence (repeatedly).

There's a part of my code, and with this I get always the 'result' on console relative at the last occurrence (for example, if I expect something like '1, 2, 3, 4, 5', I have '5 5 5 5 5')

How can I do to be sure that for loop works on the right way?

Thanks for help.

for ( counter = 0; counter < array.lenght; counter ++) {

    MongoClient.connect(url, function (err, db) {

       var query = { name: array[counter] };

       db.collection("collectionName").find(query).toArray(function (err, result) {

           // Check if 'query' value exist in the database, if yes do some stuff, otherwise do others stuff
           console.log(result); 


    }
)

EDIT: Just to let everyone know, the code finally works. Thanks for your help.

2 Answers

Try to run the below code. Let me know if it worked or not.

let fun = async function () {
    for (var counter = 0; counter < array.length; counter++) {
        await MongoClient.connect(url, function (err, db) {
            var query = { name: array[counter] };
            db.collection("collectionName").find(query).toArray(function (err, result) {
                // Check if 'query' value exist in the database, if yes do some stuff, otherwise do others stuff
                console.log(result);
            })
        })
    }
}

fun();
Related