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.

1
  • 1
    Ok, assuming the fastest way to -detect- an error in connection state would be to first attempt the operation and retry failure (stackoverflow.com/questions/8936922/…) what would be the most elegant way to encapsulate that retry, do you think? Commented Sep 8, 2016 at 22:49

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.