如果您宁愿在数据库关闭时对服务器的所有请求都失败,则本机驱动程序确实会发出重新连接事件,该事件可以在中间件中感知。
这可以正常工作并发出重新连接事件(mongodb native driver 1.3.23)
mongoose.connection.db.on('reconnect', function (ref) {
connected=true;
console.log('reconnect to mongo server.');
});
所以我的 dbconnection 中间件寻找已连接/错误/重新连接(有些事件是多余的,但不会造成伤害!) PS。最初的连接失败仍需要通过重试来处理,如上面 aaronheckmann 的回答。
mongoose.connection.on('open', function (ref) {
connected=true;
console.log('open connection to mongo server.');
});
mongoose.connection.on('connected', function (ref) {
connected=true;
console.log('connected to mongo server.');
});
mongoose.connection.on('disconnected', function (ref) {
connected=false;
console.log('disconnected from mongo server.');
});
mongoose.connection.on('close', function (ref) {
connected=false;
console.log('close connection to mongo server');
});
mongoose.connection.on('error', function (err) {
connected=false;
console.log('error connection to mongo server!');
console.log(err);
});
mongoose.connection.db.on('reconnect', function (ref) {
connected=true;
console.log('reconnect to mongo server.');
});