I have A Mongoose Connection and at some point in my program I need to close it. after logging the mongoose object several times, I have found that the following workd
mongoose.connection.base.connections[1].close();
Is There A Cleaner way to do this?
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.
1.3 close() method in the Mongo database In the Mongo universe, the close() method instructs the server to close a cursor and free the associated server resources. The server will automatically close the cursors that have no remaining results and the cursors that have been idle for a time.
You can connect to MongoDB with the mongoose.connect() method. mongoose.connect('mongodb://localhost:27017/myapp'); This is the minimum needed to connect the myapp database running locally on the default port (27017). If connecting fails on your machine, try using 127.0.0.1 instead of localhost .
Is mongoose connection Singleton? connection is a property not a method, and it holds the default connection instance on the default mongoose instance. It's not strictly a singleton pattern as you have more instances, this gives you the default instance rather than the only instance.
To close all connections in the Mongoose connection pool:
mongoose.disconnect();
Docs here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With