Why is it recommended not to close a MongoDB connection anywhere in Node.js code?
Solution 1:
You open a Db connection once with MongoClient and reuse it across your application. If you need to use multiple db's you use the .db function on the Db object to work on a different db using the same underlying pool of connections. A pool is kept to ensure a single blocking operation cannot freeze up your node.js application. Default size if 5 connections in a pool.
http://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html
I also forgot to add. As the other answer pointed out setting up a new TCP connection is EXPENSIVE timewise and memory wise that's why you reuse connections. Also a new connection will cause a new Thread to be created on MongoDB using memory on the Db as well.
Solution 2:
MongoDB pools database connections to be more efficient, so it is not unusual to have many connections open in the mongodb.log
However it is useful to close all connections when your app closes completely. This code is most excellent for doing this.
process.on('SIGINT', function() {
mongoose.connection.close(function () {
console.log('Mongoose disconnected on app termination');
process.exit(0);
});
});
Solution 3:
I am no node.js expert however I think the reason is relatively the same between most languages.
Making a connection is:
one of the most heavyweight things that the driver does. It can take hundreds of milliseconds to set up a connection correctly, even on a fast network.
( http://php.net/manual/en/mongo.connecting.pools.php )
Provided that is for PHP and the doc is a little out of date that part still applies even now and across most, if not all, drivers.
Each connection can also use a separate thread which causes obvious overhead.
It seems from:
http://mongodb.github.com/node-mongodb-native/driver-articles/mongoclient.html#the-url-connection-format
That node.js still uses connection pooling to try and stop the overhead of making a connection. This, of course, no longer applies to other drivers like the PHP one.
It opens x
amount of connections (default is 5
) to your database server and transfers work to a free connection when data is needed and so reusing old connections averting this nasty process which can cause those logs:
https://docs.mongodb.com/manual/faq/diagnostics/#why-does-mongodb-log-so-many-connection-accepted-events