I created my website with using node.js and Mongodb. when I was learned php few years ago, i saw that it is important to disconnect mysql instance after db transaction on each page to save server resources. so I did exactly same with nodejs + mongodb. but soon I realized that each connect and disconnect functions are spend lots of cost especially mongodb. is it better to keep mongodb connection alive even response to the client? is it better to keep connection alive and reconnect only it is died? i searched on google about this, but i couldn't found any helpful answers. it will be very appreciate give me some advice.
Asked
Active
Viewed 2,575 times
1 Answers
2
You should close a mongoose connection when a Node POSIX signal is happening. SIGINT process is triggered when Ctrl-C has been pressed on terminal or a server shutdown.
Another possible scenario is to close a connection when a data streaming is done. Anyway is more recommended to connect on startup and disconnect on shutdown.
This is the code for disconnection on a SIGINT signal.
// If the Node process ends, close the Mongoose connection
process.on('SIGINT', function() {
mongoose.connection.close(function () {
console.log('Mongoose disconnected on app termination');
process.exit(0);
});
});
Check this one too:

Community
- 1
- 1

Endre Simo
- 11,330
- 2
- 40
- 49