Home > Software design >  Closing MongoClient connection on exit when using MongoDB Native driver?
Closing MongoClient connection on exit when using MongoDB Native driver?

Time:04-08

Should the MongoClient connection be closed every time the server shuts down?

I have seen the following code snippet and wanted to know if this is actually valid and should be done or if it's completely unnecessary to perform a closing on exit:

// Adding listeners
function setupListeners(client: MongoClient){
    client.addListener('topologyClosed', ()=>{
        isTopologyConnected = false;
        console.warn("topologyClosed");
    })
}
process.on("exit", () => {
    console.log("EXIT - MongoDB Client disconnected");
    closeConnection()
});

//Cleanups
//catching signals and doing cleanup
['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',
    'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'
].forEach(function (signal) {
    process.on(signal, function () {
       if (isTopologyConnected){
                client.close();
            }
            process.exit(1);
    });
});

Thanks a lot.

CodePudding user response:

Should the MongoClient connection be closed every time the server shuts down?

Yes, it is a good practice to close the connection. As for every connection, mongo DB does assign a thread for its execution. If you won't close it, it keeps using the resources on the DB server.

Node.js connections use the pool to connect to DB and it can be reused while it is not being used, but it is good practice to close the connection if you are exiting the script as it won't close the connection automatically.

  • Related