Henrique Borges
Henrique Borges

Reputation: 499

Mongo TypeError: MongoClient.close is not a function

I'm building an application that closes it's database connection after a certain time of inactivity. The problem is, I can't kill it's connection with MongoClient.close() because it's always returns that a error "TypeError: MongoClient.close is not a function". What am I doing wrong?

const MongoClient = require("mongodb").MongoClient;
let mongo = {};
let db;
let disconnectTimer;
let retryTimer;
let disconnect; //Used to prevent mongo from reconnect.

mongo.disconnect = () => {
    disconnect = true;
    try {
        MongoClient.close();
    } catch (error) {
        console.warn("Error closing connection to Database =", error);
        throw {
            statusCode: 404,
            error: error.toString(),
            reason: "",
            details: ""
        };
    }
}
mongo.getDB = () => {
    if (typeof db !== "undefined" && !disconnect)
        return db;
    else
        return connect().catch((error) => {
            throw error
        }).then((db) => {return db});
}

module.exports = mongo;

Upvotes: 3

Views: 3118

Answers (2)

LuisArmando-TestCoder
LuisArmando-TestCoder

Reputation: 29

module.exports = (callback, collectionName) => {
    mongoClient.connect(connectionUrl, {
        useNewUrlParser: true,
        useUnifiedTopology: true
    })
    .then((connection) => {
        const db = connection.db(dbName);
        const collection = db.collection(collectionName);

        callback(collection, ObjectId);

        connection.close();
    });
}

Upvotes: 0

Alekhya Satya
Alekhya Satya

Reputation: 191

If db is used as the Mongo DB connection instance,then please try to use dB.close() instead of MongoClient.close().

Upvotes: 5

Related Questions