I'm using the node-mongodb-native driver with MongoDB to write a website.
I have some questions about how to manage connections:
Is it enough using only one MongoDB connection for all requests? Are there any performance issues? If not, can I setup a global connection to use in the whole application?
If not, is it good if I open a new connection when request arrives, and close it when handled the request? Is it expensive to open and close a connection?
Should I use a global connection pool? I hear the driver has a native connection pool. Is it a good choice?
If I use a connection pool, how many connections should be used?
Are there other things I should notice?
You should create a connection as service then reuse it when need.
my App.js sample
and use it wherever you want with
http://mongoosejs.com/docs/api.html
Check out the source of Mongoose. They open a connection and bind it to a Model object so when the model Object is required, a connection is made to the DB. The driver takes care of connection pooling.
I have implemented below code in my project to implement connection pooling in my code so it will create a minimum connection in my project and reuse available connection
I have been using generic-pool with redis connections in my app - I highly recommend it. Its generic and I definitely know it works with mysql so I don't think you'll have any problems with it and mongo
https://github.com/coopernurse/node-pool