Search code examples
node.jsmongodbmongoose

Mongoose autoReconnect option


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.

What I've tried:

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

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?

Thanks in advance

For anyone looking into this, take a look at this and this issue in mongoose repository.


Solution

  • 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.

    This is what I have now:

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