How mongodb connection works on concurrent requests in NodeJS express server? How mongodb connection works on concurrent requests in NodeJS express server? express express

How mongodb connection works on concurrent requests in NodeJS express server?


I have answered for both of your question separately.

1. How will the mongodb connection in the express server work?

Once a connection is created to the mongodb database.(using mongoose or any other framework) It will create a pool of connections with that. (Mongoose default pool size is 5, 100 in python) The created connection pool is maintained by the driver therefore those connections can be re-used when connections to the database are required.

The best practice is to create a new connection only once for the whole application. Once connection is created the connection object will be used as a singleton. When you connect to the database using mongoose models, separate connections are allocated from the created connection pool.

If you are going to create a new connection each time then It will cause to a connection churn.

2. How can I close the connection object in mongodb efficiently after the operation ?

I am not sure 100% about this answer. My suggestion is to disconnect the connection when the express application exits.

var db = mongoose.connect('mongodb://localhost:27017/database');    db.disconnect();

According to my knowledge what you have don in the code is correct. You have created a new connection only once. Since the connection pool is created with that you don't need to create more connections.

Please go through this link to get a clear understanding on connection pools and their usage.https://dzone.com/articles/deep-dive-connection-pooling