-
Type: Bug
-
Resolution: Works as Designed
-
Priority: Major - P3
-
None
-
Affects Version/s: 3.0.4
-
Component/s: MongoDB 3.4, Native
-
Environment:Mac OS High Sierra 10.13.3. Nodejs v9.8.0
-
Empty show more show less
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.