开发者

How to reconnect mongo automatically in node.js server?

开发者 https://www.devze.com 2023-04-08 00:02 出处:网络
Let say I have a node.js server connecting to a mongoDB.Then the mongoDB die or disconnect.Of course, 开发者_如何学Cnode.js server will lose connection.Even if I restart mongoDB, node.js server will n

Let say I have a node.js server connecting to a mongoDB. Then the mongoDB die or disconnect. Of course, 开发者_如何学Cnode.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).


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消