0

Let's imagine we have Node.JS app which is connecting to the Mongos process. But suddenly Mongos failed. How our app could now about it?

var db = null;  
mongo.MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, mydb) {
    if(err) throw err;
    db = mydb
});

..... on response we have .....
db.collection('test_collection', function(err, collection){
    collection.find({}).toArray(function(err, documents){
        // doing some work here
        // but if Mongos failed, we are blocked on this stage
    }); 
});
Jason Aller
  • 3,541
  • 28
  • 38
  • 38

1 Answers1

0

Would you not want to do the same thing that you're doing at connect, but within the function?

i.e.

...
collection.find({}).toArray(function(err, documents) {
   if(err) {
       throw err; //or do something equivalent.  It doesn't really matter if the connection has failed, as it will still throw an error.
   } else {
       ///continue processing
   }
  ....

Alternatively, if you use a 3rd party mongo manager, such as mongoose, you can do something like this globally:

mongoose.connect('mongodb://' + config.mongo.host + '/' + config.mongo.db);
var db = mongo.connection;
db.on('error', console.error.bind(console, 'connection error: '));
Stephen Wright
  • 2,908
  • 4
  • 19
  • 28