Mongoose autoReconnect选项

gus*_*nke 29 mongoose mongodb node.js

我正在尝试通过Mongoose设置MongoDB自动重新连接功能.我试图通过该选项的每一种方式都没有效果,或者至少reconnected没有发出该事件.

我尝试过的:

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 } });
Run Code Online (Sandbox Code Playgroud)

如果其中一个是正确的,reconnected则应触发事件并在控制台中记录消息,但这种情况永远不会发生.

如果在重新连接之前有延迟,是否有人知道如何配置它?

提前致谢

对于任何寻找到这一点,看看这个这个问题在猫鼬库.

Zeb*_*Lab 52

我和你有同样的问题,而robertklep的解决方案对我也没有用.我发现当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}});
Run Code Online (Sandbox Code Playgroud)

  • Mongoose在出错时不会断开连接,因此我必须明确断开连接才能重新连接 (4认同)
  • 这不再适用于 Mongoose 6 (2认同)

Ric*_*cky 16

摘自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();
Run Code Online (Sandbox Code Playgroud)


zan*_*ngw 11

最近,我调查了与MongoDBvar 的自动重新连接Mongoose.这里有一个问题,当mongoose.connectdisconnected事件处理程序中调用时,它将触发无限循环.为什么在mongoose自动重新连接时阻止SIGINT信号.

解决方案的一个方法是,mongoose.connect()只有在MongoDB之前没有连接时才能调用.该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);
    });
});
Run Code Online (Sandbox Code Playgroud)


jon*_*iba 9

只是为了后代,因为大多数这些答案都是旧的,你不应该再处理这个问题了,因为它现在已经融入了nodejs mongodb驱动程序.引用kdmon:

...重新连接现在被烘焙到mongoose并默认启用.但是,知道Mongoose默认只会尝试重新连接30秒然后放弃它可能是有用的.设置server.reconnectTries选项以增加mongoose尝试重新连接的次数.例如,您可以告诉mongoose永远不会停止尝试重新连接,如下所示:

mongoose.connect(uri, { server: { reconnectTries: Number.MAX_VALUE } });
Run Code Online (Sandbox Code Playgroud)

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


zur*_*fyx 7

@Clive 的回答非常好。尽管如此,由于使用mongoosewithPromise我在每次尝试失败后都会收到以下警告:

(node:18123) UnhandledPromiseRejectionWarning: Unhandled promise Rejection (rejection id: 1): MongoError: failed to connect to server [localhost:27017] on first connect

ES6 版本(带 Promise)

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

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();
Run Code Online (Sandbox Code Playgroud)

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