mongooseautoReconnect选项

我试图通过Mongoose来设置MongoDB自动重新连接function。 我试图通过这个选项的每一个方法都没有效果,或者至lessreconnected事件没有被排除。

我试过了:

 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事件应该被触发,并且应该在控制台中logging一条消息,但是这从来就不会发生。

如果在重新连接之前有延迟,有没有人知道如何configuration它?

提前致谢

对于任何人来看这个 ,在mongoose存储库看看这个和这个问题。

我和你有同样的问题,而robertklep的解决scheme也不适合我。 我发现当MongoDB服务停止时,会触发错误事件,但connection.readyState仍然是1(连接)。 这可能是为什么它没有自动重新连接。

这是我现在所拥有的:

  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}}); 

最近,我调查了与MongoDB var Mongoose的自动重新连接。 这里有一个问题,当在disconnected事件处理程序中调用mongoose.connect时,会触发无限循环。 为什么SIGON信号在mongoose自动重新连接时被阻塞 。

解决scheme的一个解决scheme可能是mongoose.connect()仅在与MongoDB之前没有连接时才被调用。 auto_reconnect标志可以使auto_reconnect自动重新连接到MongoDB 。 这里是代码片段。

 var mongoose = require('mongoose'); var isConnectedBefore = false; var connect = function() { mongoose.connect('mongodb://localhost/' + + 'test_dev', {server: { auto_reconnect: true }}); }; connect(); mongoose.connection.on('error', function() { console.log('Could not connect to MongoDB'); }); mongoose.connection.on('disconnected', function(){ console.log('Lost MongoDB connection...'); if (!isConnectedBefore) connect(); }); mongoose.connection.on('connected', function() { isConnectedBefore = true; console.log('Connection established to MongoDB'); }); mongoose.connection.on('reconnected', function() { console.log('Reconnected to MongoDB'); }); // Close the Mongoose connection, when receiving SIGINT process.on('SIGINT', function() { mongoose.connection.close(function () { console.log('Force to close the MongoDB conection'); process.exit(0); }); }); 

http://bites.goodeggs.com/posts/reconnecting-to-mongodb-when-mongoose-connect-fails-at-startup/中摘取

这对我工作:

 var mongoose = require('mongoose') var mongoUrl = "mongodb://localhost:27017/test" var connectWithRetry = function() { return mongoose.connect(mongoUrl, function(err) { if (err) { console.error('Failed to connect to mongo on startup - retrying in 5 sec', err); setTimeout(connectWithRetry, 5000); } }); }; connectWithRetry(); 

只是为了后人的缘故,因为这些答案大部分都是旧的,所以不需要再处理这个问题,因为它现在已经被烧入了nodejs mongodb驱动程序。 引用kdmon :

…重新连接现在被烘焙成mongoose,并默认启用。 但是,如果知道默认情况下,Mongoose将只尝试重新连接30秒,然后放弃,这可能是有用的。 设置server.reconnectTries选项来增加mongoose尝试重新连接的次数。 例如,你可以告诉mongoose永远不要停止尝试重新连接像这样:

 mongoose.connect(uri, { server: { reconnectTries: Number.MAX_VALUE } }); 

有关详细信息,请参阅连接文档和服务器选项默认值

确保mongoose也是连接到Mongo的唯一方式。 在我的情况下,我正在使用connect-mongo以Express方式存储会话,但从v0.4.0开始,它没有将auto_reconnect默认设置为true。

@克莱夫的回答非常好。 尽pipe如此,由于用Promise使用mongoose ,每次尝试失败后都会收到以下警告:

(节点:18123)UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝ID:1):MongoError:第一次连接时无法连接到服务器[localhost:27017]

ES6版本(含Promise)

我还在这个版本(完全可选)重新连接之间添加了一个小的超时时间,以防止你的屏幕(或你的logging器)被重复的消息淹没。

 import mongoose from 'mongoose'; mongoose.Promise = Promise; // Set mongoose to use ES6 Promises. const dbURI = 'mongodb://127.0.0.1:27017/myDb'; const reconnectTimeout = 5000; // ms. function connect() { mongoose.connect(dbURI, { auto_reconnect: true }) .catch(() => {}); // Catch the warning, no further treatment is required // because the Connection events are already doing this // for us. } const db = mongoose.connection; db.on('connecting', () => { console.info('Connecting to MongoDB...'); }); db.on('error', (error) => { console.error(`MongoDB connection error: ${error}`); mongoose.disconnect(); }); db.on('connected', () => { console.info('Connected to MongoDB!'); }); db.once('open', () => { console.info('MongoDB connection opened!'); }); db.on('reconnected', () => { console.info('MongoDB reconnected!'); }); db.on('disconnected', () => { console.error(`MongoDB disconnected! Reconnecting in ${reconnectTimeout / 1000}s...`); setTimeout(() => connect(), reconnectTimeout); }); connect(); 

有关连接事件的更多信息。

这是对Clive的答案的一个改进,它在连接尝试之间设置了至less5秒。

 var db = mongoose.connection; var lastReconnectAttempt; //saves the timestamp of the last reconnect attempt db.on('error', function(error) { console.error('Error in MongoDb connection: ' + error); mongoose.disconnect(); }); db.on('disconnected', function() { console.log('MongoDB disconnected!'); var now = new Date().getTime(); // check if the last reconnection attempt was too early if (lastReconnectAttempt && now-lastReconnectAttempt<5000) { // if it does, delay the next attempt var delay = 5000-(now-lastReconnectAttempt); console.log('reconnecting to MongoDB in ' + delay + "mills"); setTimeout(function() { console.log('reconnecting to MongoDB'); lastReconnectAttempt=new Date().getTime(); mongoose.connect(dbURI, {server:{auto_reconnect:true}}); },delay); } else { console.log('reconnecting to MongoDB'); lastReconnectAttempt=now; mongoose.connect(dbURI, {server:{auto_reconnect:true}}); } }); 

要在重试时没有请求阻塞多次重试我必须设置bufferMaxEntries: 0

 const dbUri = 'mongodb://localhost/some_db'; const dbOptions = { useMongoClient: true, autoReconnect: true, reconnectTries: Number.MAX_VALUE, bufferMaxEntries: 0 }; mongoose.connect(dbUri, dbOptions).catch(err => process.exit(1)); 

阅读文档后,我很确定你有select错误。 连接选项string应如下所示:

 mongoose.connect("mongodb://localhost:27017/db", { socketOptions: { // This option is on by default, but why not set it explicitly autoReconnect: true }, // This options is 1 second by default, its possible the ha // takes longer than 30 seconds to recover. reconnectInterval: 5000, // This options is 30 by default, why not make it 60 reconnectTries: 60 }) 

检查这个页面: http : //mongoosejs.com/docs/api.html

基于@zangw的答案,我已经完成了这个数据库初始化函数为我的应用程序

 const mongoose = require('mongoose') const RETRY_TIMEOUT = 3000 module.exports = function initDB () { mongoose.Promise = global.Promise const options = { autoReconnect: true, useMongoClient: true, keepAlive: 30000, reconnectInterval: RETRY_TIMEOUT, reconnectTries: 10000 } let isConnectedBefore = false const connect = function () { return mongoose.connect(process.env.MONGODB_URL, options) .catch(err => console.error('Mongoose connect(...) failed with err: ', err)) } connect() mongoose.connection.on('error', function () { console.error('Could not connect to MongoDB') }) mongoose.connection.on('disconnected', function () { console.error('Lost MongoDB connection...') if (!isConnectedBefore) { setTimeout(() => connect(), RETRY_TIMEOUT) } }) mongoose.connection.on('connected', function () { isConnectedBefore = true console.info('Connection established to MongoDB') }) mongoose.connection.on('reconnected', function () { console.info('Reconnected to MongoDB') }) // Close the Mongoose connection, when receiving SIGINT process.on('SIGINT', function () { mongoose.connection.close(function () { console.warn('Force to close the MongoDB connection after SIGINT') process.exit(0) }) }) } 

有一些区别:我已经添加了一些选项,以防止连接closures的问题 – 30次自动重试后没有重新连接,只是MongoError:拓扑被破坏的任何操作,没有重新连接; 也连接后添加.catch以防止未处理的承诺拒绝):