How to automatically connect mongo on node.js server?

Let's say I have a node.js server connecting to mongoDB. Then mongoDB dies or shuts down. Of course the node.js server will lose the connection. Even if I restart mongoDB, the node.js server won't automatically connect to the new mongodb, even if it is running on the same machine with the same port. I need to either restart the node.js server or write my own procedure somehow to rewire it.

Is there any node module to handle reconnection? and less aggressive. (i.e. won't ask for a connection every second).

+2


source to share


1 answer


The answer to this question will depend on your driver version and your specific code.

The most recent driver versions should support pooling . This usually means that you might get an exception when trying your first connection, but you should be able to reconnect.



Your implementation is also important. There are several ways to do this. Some people open a connection outside of the web server startup, others do it in response to requests.

If you have a pool of connections, you should be able to "open a connection" on every request. After a reboot, you will have to handle errors correctly, but you do not need to restart your Node.

+1


source







All Articles