OneCompiler

How to reconnect to MongoDB from NodeJS in case of MongoDB restarts & Network failures ?

I am using MongoDB's official NodeJS driver in my NodeJS project, when there is a network issue or MongoDB restarted my application loosing the connection and failing in all further calls. How can I keep retying in such scenarios?

1 Answer

6 years ago by

We can use reconnectTries & autoReconnect parameters while creating a MongoDB connection. The following sample codes show you how to use that.

const MongoClient = require('mongodb').MongoClient;

var settings = {
  reconnectTries : Number.MAX_VALUE,
  autoReconnect : true
};

MongoClient.connect(mongoDbUri, settings, function(err, dbref) {
  if (!err) {
    console.log("Mongodb connected. url:" + mongoDbUri);
    // handle dbref
  }else{
    console.log(err);
  }
});

6 years ago by Karthik Divi