Reliably reconnect to MongoDB

2020-02-02 12:30发布

UPDATE: I am using the 2.1 version on the driver, against 3.2

I have a node application that uses MongoDB. The problem I have is that if the MongoDB server goes down for any reason, the application doesn't reconnect. To get this right, I based my tests on the code in this official tutorial.

var MongoClient = require('mongodb').MongoClient
  , f = require('util').format;

MongoClient.connect('mongodb://localhost:27017/test', 

// Optional: uncomment if necessary
// { db: { bufferMaxEntries: 3 } },


function(err, db) {
  var col = db.collection('t');

  setInterval(function() {
    col.insert({a:1}, function(err, r) {
      console.log("insert")
      console.log(err)

      col.findOne({}, function(err, doc) {
        console.log("findOne")
        console.log(err)
      });
    })
  }, 1000)
});

The idea is to run this script, and then stop mongod, and then restart it. So, here we go:

TEST 1: stopping mongod for 10 seconds

Stopping MongoDb for 10 seconds does the desired result: it will stop running the queries for those 10 seconds, and then will run all of them once the server is back ip

TEST 2: stopping mongod for 30 seconds

After exactly 30 seconds, I start getting:

{ [MongoError: topology was destroyed] name: 'MongoError', message: 'topology was destroyed' }
insert

{ [MongoError: topology was destroyed] name: 'MongoError', message: 'topology was destroyed' }

The trouble is that from this on, when I restart mongod, the connection is not re-establised.

Solutions?

Does this problem have a solution? If so, do you know what it is? Once my app starts puking "topology was destroyed", the only way to get everything to work again is by restarting the whole app...

7条回答
我只想做你的唯一
2楼-- · 2020-02-02 12:55

With mongodb driver 3.1.10, you can set up your connection as

MongoClient.connect(connectionUrl, {
    reconnectInterval: 10000, // wait for 10 seconds before retry
    reconnectTries: Number.MAX_VALUE, // retry forever
}, function(err, res) {
    console.log('connected') 
})

You do not have to specify autoReconnect: true as that's the default.

查看更多
登录 后发表回答