3

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.

thelearner
  • 1,440
  • 3
  • 27
  • 58

1 Answers1

1

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.

Apoorva Chikara
  • 8,277
  • 3
  • 20
  • 35
  • Thanks a lot! Do you believe the code snippet I've provided for closing connections is of value/good quality? – thelearner Apr 07 '22 at 09:56
  • 1
    Yes, it is good. These are POSIX signals and you can check them [here](https://dsa.cs.tsinghua.edu.cn/oj/static/unix_signal.html) and add or delete them for your application. – Apoorva Chikara Apr 07 '22 at 10:00
  • I'm sorry to bother you again my friend, but do you know by any means how one could determine the ideal maxPoolSize? https://stackoverflow.com/questions/71781530/configuring-the-ideal-maxpoolsize-on-mongodb-native-driver – thelearner Apr 07 '22 at 11:41