Reputation: 15006
I'm writing a script to modify all entries in a database. Here is a start to log them all.
MongoClient = require('mongodb').MongoClient.connect("mongodb://localhost:27017/mydb", { useNewUrlParser: true } ),
(async () =>{
let client;
try {
client = await MongoClient;
let collection = client.db("booliscraper").collection("sold");
let docs = await collection.find();
docs.forEach((doc) => {
console.log(doc);
})
} catch(err) {
log(err)
}
})();
This works fine, but I want to close the db-connection somehow. I tried closing it outsidthe try/catch, but that seems to close the connection before all items are itterated through. Don't understand why.
...
} catch(err) {
log(err)
}
client.close();
})();
Upvotes: 0
Views: 70
Reputation: 416
You can add finally block and close MongoDB connection there
(async () => {
let client;
try {
client = await MongoClient;
let collection = client.db("booliscraper").collection("sold");
let docs = await collection.find();
await docs.forEach((doc) => {
console.log(doc);
})
} catch (err) {
log(err)
} finally {
client.close()
}})();
Here is reference try...catch
Upvotes: 0
Reputation: 2161
docs
, the result of <Collection>.find()
, is a cursor; and <Cursor>.forEach()
is an async function.
Meaning your client.close()
effectively gets called before you finished iterating over the cursor.
You may pass a second callback to forEach, that gets executed once the cursor has been exhausted:
MongoClient = require('mongodb').MongoClient.connect("mongodb://localhost:27017/mydb", { useNewUrlParser: true } ),
(async () =>{
let client;
try {
client = await MongoClient;
let collection = client.db("booliscraper").collection("sold");
let docs = await collection.find();
docs.forEach((doc) => {
console.log(doc);
}, () => {
//cursor is exhausted, close connection
client.close();
})
} catch(err) {
log(err)
}
})();
For more information, this is documented in the Node.js Mongo DB Driver API.
Upvotes: 2