I wanna use promises for mongodb in NodeJS. So, I had some code:
const mongo = require('mongodb').MongoClient;
const config = require('./config.json');
mongo.connect(config.URI, function (err, client) {
const db = client.db("INDFLORIST");
const collection = db.collection('API');
collection.insertOne({name: 'Roger'}, function (err, res) {
if (err) throw err;
console.log("Document inserted");
client.close();
});
});
Then I've convert callback
to promise
:
const mongo = require('mongodb').MongoClient;
const config = require('./config.json');
mongo.connect(config.URI).then(client => {
const db = client.db("INDFLORIST");
const collection = db.collection('API');
return collection.insertOne({name: 'Roger'});
})
.then(function(result) {
console.log("Document inserted");
}).then(client => {
client.close();
})
.catch(err => {
console.error(err);
});
But this script invoke error: TypeError: Cannot read property 'close' of undefined.
Can u help me? How solve this problem?