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()
, without closing the connection previously - does it stay open? Is it closed automatically? If so, who cares about that? Node.js? The TCP/IP stack? MongoDB? …? And: When does that happen?
Does it make a difference if I hit <Ctrl>+<C>
?
1.3 close() method in the Mongo database The server will automatically close the cursors that have no remaining results and the cursors that have been idle for a time. Here is what the query syntax will look like.
javascript, node.js, database, mongodb The MongoClient#close() method API documentation says: Close the client, which will close all underlying cached resources, including, for example, sockets and background monitoring threads.
The most simple way to allow MongoDB to reconnect is to define a reconnectTries in an options when passing it into MongoClient . Any time a CRUD operation times out, it will use the parameters passed into MongoClient to decide how to retry (reconnect). Setting the option to Number.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With