Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing MongoClient connection on exit when using MongoDB Native driver?

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.

like image 706
thelearner Avatar asked Dec 13 '25 20:12

thelearner


1 Answers

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.

like image 73
Apoorva Chikara Avatar answered Dec 16 '25 23:12

Apoorva Chikara



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!