0

I am having a problem using the MongoDB client for Nodejs (3.0.4), with Node (v9.8.0). The issue is that when I run a query against a database, it works when it is called one time, but not when it is called under a loop.

See the following code:

'use strict';

// Load modules
const Mongo       = require('mongodb');
const MongoClient = Mongo.MongoClient;


async function runOnce() {
    let result = await runBasicMongoQuery();
    console.log(result);

    process.exit(0);

}

async function runManyTimes() {

    [1,2,3,4,5].forEach(async (x) => {

        let result = await runBasicMongoQuery();
        console.log(result);
    });

    process.exit(0);
}



async function runBasicMongoQuery() {

    try {
        console.log(`Creating client:`);
        let client = await MongoClient.connect('mongodb://localhost:27017/test');
        console.log(`\tclient: ${!!client}`);

        console.log(`Creating db:`);
        let db     = client.db();
        console.log(`\tdb: ${!!db}`);

        console.log(`Retrieve collection:`);
        let coll   = db.collection('temp');
        console.log(`\tcoll: ${!!coll}`);

        console.log(`Run Query:`);
        let result = await coll.find({ name: 'me' }).sort({ name: 1 }).toArray();
        console.log(`\tresult: ${!!result}`);

        return result;
    } catch(err) {

        console.log(err);
    }
}

When I run the function runOnce() I get a successful execution:

Creating client:
        client: true  
Creating db:
        db: true 
Retrieve collection:
        coll: true 
Run Query:
        result: [ { _id: 5aabfc0763abc840a19d927c, name: 'me' } ]

When I run the command runManyTimes() I get the following response:

Creating client:
Creating client:
Creating client:
Creating client:
Creating client:

Notice that this fails silently at the MongoClient.connect(...). No error raised, no nothing.

Why is this failing when invoking the command inside a loop that uses async / await?

Thanks.

agarcian
  • 3,909
  • 3
  • 33
  • 55

1 Answers1

1

It's not about MongoDB, but about any async call you do inside a .forEach() loop, check this question.

In your particular case I don't think it's failing, process.exit(0) is just forcing the process to exit before you're getting back the result.

Antonio Val
  • 3,200
  • 1
  • 14
  • 27
  • Actually it was all about the forEach not working on async. It never brings a result, just fails silently. Your answer solved the issue. Thanks! – agarcian Mar 16 '18 at 19:15