Home > OS >  Unable to close mongoose connection in node.js
Unable to close mongoose connection in node.js

Time:11-08

I am unable to close mongoose connection when I am storing mongoose.connection in a variable called db and creating a separate method to closing the connection via variable db I have tried both method db.close & mongoose.disconnect()

const mongoose = require('mongoose');

var db;

const connectToDB = function (callback) {
    let dbUrl;
    if (environmentTokens.enviroment === "test") {
        dbUrl = localDBUrl;
    } else {
        dbUrl = environmentTokens.mongoDBUrl;
    }
    mongoose.connect(dbUrl);
    db = mongoose.connection

    db.on('error', (err) => {
        tracer.error('Connection error with database', err);
    })

    db.on('connected', () => {
        tracer.info('Connected with database', dbUrl);
        console.log('Mongoose default connection connected');
        callback();
    })
};

const getDB = function () {
    return db;
};

const disconnectDB = function () {
    db.close(function () { 
        console.log('Mongoose default connection disconnected through app termination')}) 
    // mongoose.disconnect(function () { 
    //     console.log('Mongoose default connection disconnected through app termination')}) 

}
module.exports = {
    connectToDB, disconnectDB, getDB
};

And calling the disconnectDB method from index.js file

process.on('SIGINT', () => {
  disconnectDB();
  process.exit()
})

CodePudding user response:

The connection is closing, but your program is exiting before the callback is invoked.

To confirm, try:

process.on('SIGINT', () => {
  disconnectDB(true);
})
const disconnectDB = function (exit=false) {
    db.close(function () { 
        console.log('Mongoose default connection disconnected through app termination')}) 
    if (exit) process.exit()
  })
    // mongoose.disconnect(function () { 
    //     console.log('Mongoose default connection disconnected through app termination')}) 

}
  • Related