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 is just as easy, using our example from earlier:
adminConnection.close(function () { console.log('Mongoose connection adminConnection closed'); });
Closing when the Node process ends
As a rule you should tidy up the connections when your Node application...