17

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
  • Are you able to run mongod and look at the output as process.exit() executes? We're using mongoose which does a fair bit of connection management so I doubt what I'd post would be accurate. May 2, 2016 at 11:16

2 Answers 2

16

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.

1
  • Note that newer versions of node will throw uv_signal_start EINVAL Error when you're trying to work with SIGKILL or SIGSTOP
    – ttemple
    Aug 2, 2021 at 20:49
0

I've tested with CTRL+C, and the connections are closing automatically. The picture bellow shows connection after running server.js and after closing it. It shows that the current connection is 1 because i'm running mongo from terminal. Try it yourself! Mongo database instance from terminal

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.