I am using node.js & MongoDB, and I have asynchronous code (async.queue
) to update MongoDB.
When all the tasks in the queue is finished, I call
db.close() // db is a Mongo client instance
hence all connections used by the tasks are closed. However, in rare condition, I found there are open connections that are never closed seen in mongoDB logs. So after a few weeks, there will be hundred of connections never closed.
I researched and found that maybe I should set this option maxIdleTimeMS
, but this option is not supported by all drivers (node.js driver does not support this option).
Even if I can fine tune my code to make sure there is no such condition that close()
is not called. I am still wondering what if an app does not call db.close()
for some reason (or as an extra insurance), is there any way to prevent hanging connections in MongoDB?
open(function (err, db) { db. close(); }); // Open another connection db. open(function (err, db) { db. close(); });
There is no need for closing the connection explicitly. This way the application avoids creating and closing connections (which is an expensive operation).
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.
Any new connection you establish that has exactly the same connection string will be able to reuse the connection from the pool. We strongly recommend that you always close the connection when you are finished using it so that the connection will be returned to the pool.
One liners to start or stop mongodb service using command line; To start the service use: NET START MONGODB. To stop the service use: NET STOP MONGODB.
nodejs mongodb driver drops connection when idle
Handling MongoDB disconnect/reconnects from Node
looks like after some time of idle, connection is closed.
It is not clear which driver is used, but in one of that post there is link to docs:
http://mongodb.github.io/node-mongodb-native/api-generated/server.html#server
Set keepAlive to 0, and your connection will be terminated...
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