Why is it recommended not to close a MongoDB connection anywhere in Node.js code?

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.

Leave a Comment