Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose Close Connection

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?

like image 592
Ari Porad Avatar asked Apr 14 '13 14:04

Ari Porad


People also ask

Do I need to close the connection in mongoose?

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.

How do I close a connection in MongoDB?

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.

How do I open a mongoose connection?

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?

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.


1 Answers

To close all connections in the Mongoose connection pool:

mongoose.disconnect();

Docs here.

like image 177
JohnnyHK Avatar answered Sep 22 '22 07:09

JohnnyHK