I am using the mongodb
driver to connect to a MongoDB server from a Node.js application.
Supposed my application crashes, or I call process.exit()
The answer is no. DB connections don't gracefully shut down when you exit (or crash).
To do that you should use something similar to:
// Create a function to terminate your app gracefully:
function gracefulShutdown(){
// First argument is [force], see mongoose doc.
mongoose.connection.close(false, () => {
console.log('MongoDb connection closed.');
});
});
}
// Ask node to run your function before exit:
// This will handle process.exit():
process.on('exit', gracefulShutdown);
// This will handle kill commands, such as CTRL+C:
process.on('SIGINT', gracefulShutdown);
process.on('SIGTERM', gracefulShutdown);
process.on('SIGKILL', gracefulShutdown);
// This will prevent dirty exit on code-fault crashes:
process.on('uncaughtException', gracefulShutdown);
There are also some packages to handle this behavior, but this is usually very straightforward, and simple to implement.