Handle lost connection to mongo db from nodejs

limitium picture limitium · Jan 21, 2014 · Viewed 11.7k times · Source

I'm trying to get "connection lost" or something similar when connection lost between nodejs and mongodb server. I use native driver and has following code

var mongo = require('mongodb');
var server = new mongo.Server('host', 'port', {
    auto_reconnect: true,
    socketOptions: {
        keepAlive: 10,
        connectTimeoutMS: 1000,
        socketTimeoutMS: 0
    }
});
var db = new mongo.Db(
    'dbname',
    server,
    {
        w: 1,
        wtimeout: 1000,
        numberOfRetries: 100,
        auto_reconnect: true
    }
);

db.on('close', function () {
    console.log('Error...close');
});
db.on('error', function (err) {
    console.log('Error...error', err);
});
db.on('disconnect', function (err) {
    console.log('Error...disconnect', err);
});
db.on('disconnected', function (err) {
    console.log('Error...disconnected', err);
});
db.on('parseError', function (err) {
    console.log('Error...parse', err);
});
db.on('timeout', function (err) {
    console.log('Error...timeout', err);
});

db.collection('collectionName',function(err, collection){
    if(err){
        console.log('Error...collection', err);
        return;
    }

    // set breakpoint here and break connection to mongo db server  
    collection.insert({}, function (err, data) {
        if (err) {
            console.log('Error...insert', err);
        }
        console.log('Fine!');
    });
});

No timeout or error apear around 20 minutes and insert is freezed. After that I got "Error...insert" with connection lost error.

I tried to set socketTimeoutMS = 10000 and keepAlive = 1 for example, but socketTimeoutMS rise "timeout" event constantly after 10000 and doesn't take into account keepAlive settings or even queries to mongodb.

Also wtimeout works only if we have connection to mongodb server and has a longtime query. If connection is lost it doesn't works.

So how can I get event or err when I lost conneciton? Or reduce 20 minute query freeze?

Answer

Gianfranco P. picture Gianfranco P. · Mar 11, 2014

If have the mongodb server process running, run this example. After, if you stop the server process, you'll see Error...close being displayed. All possible events for the "on" function can be found here

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

// Connect to the db
MongoClient.connect('mongodb://localhost:27017/exampleDb', function(err, db) {
  if(err) {
    return console.dir(err);
  }
  console.log('We are connected');
  // db.close();
  db.on('close', function () {
    console.log('Error...close');
  });
});