mongooseconnectTimeoutMScallback

当断开连接并connectTimeoutMS结束时,我想要做的事情。 我在我的mongooseconfiguration中使用这个选项:

var options = { server: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 } } }; 

所以30秒后,它放弃尝试重新连接。 有没有什么好的解决scheme,我可以处理这个放弃事件 ? 我想在connectTimeoutMS结束后做一些事情。 它应该首先尝试重新连接30秒,然后如果失败 – 发出警告,表示无法重新连接。

你保持活力太低。 从官方文档 –

对于长时间运行的应用程序,通常谨慎的做法是使keepAlive的数毫秒。 没有它,一段时间后,你可能会开始看到“连接closures”的错误,似乎没有理由。 如果是这样,读完这个之后,你可以决定启用keepAlive

您必须查看您的mongoose.connectcallback中的error对象。

 var mongoose = require('mongoose'); var retryAttempts = 0; var options = { server: { socketOptions: { keepAlive: 1, connectTimeoutMS: 1000 } } }; function mongoConnect() { mongoose.connect('mongodb://127.1.2.3/test', options, function (error) { if (error && error.message.indexOf('timed out') > -1) { if (retryAttempts++ < 5) { console.log('Retrying...'); mongoConnect(); } else { console.log('Could not connect after %d attempts', retryAttempts-1); } } }); } mongoConnect(); 

例如,您可以通过使用async.doWhilst函数来避免recursion方法。