Reliably reconnect to MongoDB

There are 2 connection options that control how mongo nodejs driver reconnects after connection fails

  • reconnectTries: attempt to reconnect #times (default 30 times)
  • reconnectInterval: Server will wait # milliseconds between retries
    (default 1000 ms)

reference on mongo driver docs

Which means that mongo will keep trying to connect 30 times by default and wait 1 second before every retry. Which is why you start seeing errors after 30 seconds.

You should tweak these 2 parameters based on you needs like this sample.

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

MongoClient.connect('mongodb://localhost:27017/test', 
    {
        // retry to connect for 60 times
        reconnectTries: 60,
        // wait 1 second before retrying
        reconnectInterval: 1000
    },

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

This will try 60 times instead of the default 30, which means that you’ll start seeing errors after 60 seconds when it stops trying to reconnect.

Sidenote: if you want to prevent the app/request from waiting until the expiration of the reconnection period you have to pass the option bufferMaxEntries: 0. The price for this is that requests are also aborted during short network interruptions.

Leave a Comment

techhipbettruvabetnorabahisbahis forumu