猫鼬自动重新连接选项 [英] Mongoose autoReconnect option
问题描述
我正在尝试通过Mongoose设置MongoDB自动重新连接功能.我尝试通过该选项的每种方式均无效,或者至少没有发出reconnected
事件.
I'm trying to set up the MongoDB auto reconnection feature via Mongoose. Every way that I have tried to pass the option has had no effect, or at least the reconnected
event isn't being emitted.
我尝试过的事情:
mongoose.createConnection("mongodb://localhost:27017/test", { auto_reconnect: true });
mongoose.createConnection("mongodb://localhost:27017/test", { autoReconnect: true });
mongoose.createConnection("mongodb://localhost:27017/test", { server: { auto_reconnect: true } });
mongoose.createConnection("mongodb://localhost:27017/test", { server: { autoReconnect: true } });
如果其中之一是正确的,则应该触发reconnected
事件,并在控制台中记录一条消息,但这永远不会发生.
If one of these is correct, the reconnected
event should be triggered and a message should be logged in the console, however this never happens.
如果重新连接之前有延迟,那么有人知道如何配置吗?
If there is a delay before the reconnection, does anyone know how to configure it?
预先感谢
对于任何对此感兴趣的人,请查看此和
For anyone looking into this, take a look at this and this issue in mongoose repository.
推荐答案
我和你有同样的问题,而robertklep的解决方案对我也不起作用.我发现MongoDB服务停止时,触发了一个错误事件,但是connection.readyState仍然为1(已连接).这可能就是为什么它没有自动重新连接的原因.
I had the same question as you, and robertklep's solution didn't work for me either. I found when MongoDB service is stopped, an error event is triggered, but the connection.readyState is still 1 (connected). That may be why it didn't auto reconnect.
这就是我现在拥有的:
var db = mongoose.connection;
db.on('connecting', function() {
console.log('connecting to MongoDB...');
});
db.on('error', function(error) {
console.error('Error in MongoDb connection: ' + error);
mongoose.disconnect();
});
db.on('connected', function() {
console.log('MongoDB connected!');
});
db.once('open', function() {
console.log('MongoDB connection opened!');
});
db.on('reconnected', function () {
console.log('MongoDB reconnected!');
});
db.on('disconnected', function() {
console.log('MongoDB disconnected!');
mongoose.connect(dbURI, {server:{auto_reconnect:true}});
});
mongoose.connect(dbURI, {server:{auto_reconnect:true}});
这篇关于猫鼬自动重新连接选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!