Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a connection to MongoDB automatically closed on process.exit()?

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>?

like image 325
Golo Roden Avatar asked May 02 '16 09:05

Golo Roden


People also ask

Does MongoDB close connection automatically?

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.

How do I close a connection in MongoDB?

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.

How do I keep my MongoDB connection open?

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.


1 Answers

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.

like image 67
Selfish Avatar answered Sep 28 '22 03:09

Selfish