Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 979
Henrique Borges Avatar asked Apr 18 '26 13:04

Henrique Borges


1 Answers

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

like image 130
Alekhya Satya Avatar answered Apr 21 '26 07:04

Alekhya Satya