2

If I receive a SIGINT/SIGTERM (e.g. ctrl+c) then I must gracefully stop my app and close all connections to the mongodb server.

Most documentation/tutorials state that to stop a connection (or pool of connections), I must use mongoose.disconnect() - which calls .close() on connections in the pool.

However all those docs also say this should be done after all pending writes are completed.

How can I know this when I receive a signal event (e.g. SIGINT, SIGTERM, etc.)? Does mongoose have graceful shutdown functionality, or will I lose data when I call disconnect()?

(I'm using the latest bits.)

lonix
  • 14,255
  • 23
  • 85
  • 176
  • I know how to listen for signal events. What I don't know is how to ensure all writes are flushed. How to do so **gracefully**, if at all possible. – lonix Feb 03 '19 at 13:13

2 Answers2

0

To receive SIGINT signal and stop a connection you can use following code:

process.on('SIGINT', () => {
    mongoose.disconnect().then(() => {
        process.exit();
    });
});
mat.mik
  • 97
  • 1
  • 8
0

Try this one;

process.on ("SIGINT", async() => {
  await mongoose.connection.close ();
  process.exit (0)
});