10

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.

Zlatko
  • 18,936
  • 14
  • 70
  • 123
  • 1
    Ok, assuming the fastest way to -detect- an error in connection state would be to first attempt the operation and retry failure (http://stackoverflow.com/questions/8936922/is-inserting-a-new-database-entry-faster-than-checking-if-the-entry-exists-first) what would be the most elegant way to encapsulate that retry, do you think? – Montagist Sep 08 '16 at 22:49

1 Answers1

9

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.

moka
  • 22,846
  • 4
  • 51
  • 67
  • 1
    That's what I do currently - I do, ie. users.find({}, function(err, res) { if (err).... else ...});. I wonder if there is a way to test the connection before sending a request so that I first try to restore the connection. – Zlatko Jul 22 '13 at 11:49
  • 3
    I don't see how this addresses the question at all. You get an error. That error could've been for a number of things, not all involving the connection. – Montagist Sep 08 '16 at 22:50