Search code examples
javascriptmongodbes6-promise

How to close connect in mongo by promises?


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?


Solution

  • You can create some external variable _client_ and after successful connection assign client to it, then you can use _client_ to close connection in last then callback

    const mongo = require("mongodb").MongoClient;
    const config = require("./config.json");
    let _client_; // <-- external variable
    mongo.connect(config.URI).then(client => {
        _client_ = client; // <-- assing real client to it
        const db = client.db("INDFLORIST");
        const collection = db.collection("API");
        return collection.insertOne({name: "Roger"});
    }).then(function (result) {
        console.log("Document inserted");
    }).then(() => {
        _client_.close(); // <-- close connection
    }).catch(err => {
        console.error(err);
    });
    

    You can also pass it thru all then callbacks

    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(() => client);
    }).then(function (client) {
        console.log("Document inserted");
        return client;
    }).then(client => {
        client.close();
    }).catch(err => {
        console.error(err);
    });