I'm trying to use MongoDB with Promises in Node 4.x
In this example I want to:
- Connect to my mongodb
- THEN delete everything with a given Key
- THEN insert one record
- THEN close the connection
luckily the mongodb client spits out promises when you don't give it a callback. Here's what I came up with.
const MongoClient = require('mongodb').MongoClient;
const test = require('assert');
function insertDoc(doc, collName) {
return MongoClient.connect('mongodb://localhost:27017/myDB')
.then(db => {
const col = db.collection(collName);
return col.deleteMany({ 'Key': doc.key })
.then(() => col.insertOne(doc))
.then(result => test.equal(1, result.insertedCount))
.then(() => db.close);
});
}
The code seems to work but the nested .then()
"feels" wrong. Any ideas how to do it so that the db
object can be used when I'm ready to .close()
it?