Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if MongoDB connection is alive in Node.js

I have an app with MongoDB as backend. When the app is started, I set up the connection and use it later on requests.

But if in the mean time my db conncetion fails (ie. mongod crashes), how can I check that on the request time?

To clarify a bit:

  • currently I have an "api.js", which does db.once('open', function../* setup */)
  • on request, I do db.find(conditions, function(err, res) { if (err) ...else ...}).

What I want to do is check if the connection is alive before the db.find() clause. So if it is down, I can try to restart the db connection.

P.S. I know, I should probably set some sort of a connection pool or similar instead of keeping the connection alive all the time, but right now it's set as it is.

like image 581
Zlatko Avatar asked Jul 22 '13 11:07

Zlatko


1 Answers

You can use event to handle it as callback.
And maybe have your global variable that will identify that it is not connected.

You can have separate db.js file, that will behave as module. And you can have function to get collection from it.

var mongodb = require('mongodb');
var client;
var collections = { };

new mongodb.Db( ... ).open((function (err, c) {
  if (!err) {
    client = c;
    client.on('close', function() {
      client = null; // clear client
      collections = { }; // clear old collections
      // connection closed
    });
  } else {
    // error connecting
  }
});

// get collection
exports.get = function(name, callback) {
  if (client) {
    if (!collections[name]) {
      collections[name] = new mongodb.Collection(client, name);
    }
    callback(null, collections[name]);
  } else {
    // can perform reconnecting and then get collection and call callback
    callback(new Error('not connected'));
  }
}

So to use it:

var db = require('./db.js');

db.get('users', function(err, collection) {
  if (!err) {
    collection.find({ ...
  } else {
    console.log(err);
  }
});

Sorry, just noticed you are using Mongoose, which can be different slightly.

like image 86
moka Avatar answered Oct 20 '22 07:10

moka