Closing the connection

As we have already seen, the general best practice is to open your connection at application start up, and keep it open. However, there are times when you will want to close the connection. For example, if your application is shutting down, or restarting, the database connection needs to be manually closed, or if you are running a single-hit script rather than a persistent application.

Calling the close command

Each Mongoose connection has a close() method that takes an optional callback function.

If you are using the default connection you call it like the following code snippet does:

mongoose.connection.close(function () {
  console.log('Mongoose default connection closed');
});

Calling the close() method on a named connection ...

Get Mongoose for Application Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.