Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In MongoDB, how to make sure all connection will be closed if close() might not get called sometimes?

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?

like image 578
Joe Huang Avatar asked Apr 23 '16 12:04

Joe Huang


People also ask

How do I close all connections in MongoDB?

open(function (err, db) { db. close(); }); // Open another connection db. open(function (err, db) { db. close(); });

Do you need to close MongoDB connection?

There is no need for closing the connection explicitly. This way the application avoids creating and closing connections (which is an expensive operation).

Do you need to close Mongoose 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.

Should I close DB connection after query?

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.

How do I close a MongoDB server?

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.


1 Answers

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...

like image 157
Michał Zaborowski Avatar answered Sep 27 '22 19:09

Michał Zaborowski