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.

4

1 回答 1

9

您可以使用事件将其作为回调处理。
也许你的全局变量会识别它没有连接。

您可以有单独的db.js文件,它将作为模块。并且您可以拥有从中获取收藏的功能。

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'));
  }
}

所以要使用它:

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

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

抱歉,刚刚注意到您使用的是 Mongoose,可能会略有不同。

于 2013-07-22T11:46:45.257 回答