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

后端 未结 1 772
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-19 12:43

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()

相关标签:
1条回答
  • 2021-02-19 13:27

    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.

    0 讨论(0)
提交回复
热议问题