2

Let say I have a node.js server connecting to a mongoDB. Then the mongoDB die or disconnect. Of course, node.js server will lose connection. Even if I restart mongoDB, node.js server will not connect to the new mongodb automatically even it is running on the same machine with same port. I need to either restart Node.js server or somehow write my own routine to reconnect it.

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

1 Answer 1

1

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

The most recent driver versions should support connection pooling. This typically means that you may get an exception when attempting a first connection, but you should be able to re-connect.

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

If you have connection pooling, then you should be able to "open a connection" on every request. You will have to handle the errors correctly after reboot, but you should not need to restart the Node environment.

1
  • I know this thread is really old, but I have the same question. I'm using Mongoose version 4 to connect to Mongodb and am unable to get my node app to reconnect to the mongodb server after it is brought back up. Can you please provide a sample code about the possible ways to implement the reconnection without having to restart node every time? (I'm a newbie at this). Thanks.
    – coder101
    May 31, 2019 at 20:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.