如何在Node.JS中检查mongos连接是否仍然存在?

时间:2014-02-26 10:49:55

标签: javascript node.js mongodb v8 node-mongodb-native

让我们假设我们有Node.JS应用程序连接到Mongos进程。但突然蒙古人失败了。我们的应用程序现在可以如何处理它?<​​/ p>

var db = null;  
mongo.MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, mydb) {
    if(err) throw err;
    db = mydb
});

..... on response we have .....
db.collection('test_collection', function(err, collection){
    collection.find({}).toArray(function(err, documents){
        // doing some work here
        // but if Mongos failed, we are blocked on this stage
    }); 
});

1 个答案:

答案 0 :(得分:0)

你不想做你在连接时做的事情,但在函数内吗?

即。

...
collection.find({}).toArray(function(err, documents) {
   if(err) {
       throw err; //or do something equivalent.  It doesn't really matter if the connection has failed, as it will still throw an error.
   } else {
       ///continue processing
   }
  ....

或者,如果您使用第三方mongo管理器,例如mongoose,您可以在全球范围内执行此类操作:

mongoose.connect('mongodb://' + config.mongo.host + '/' + config.mongo.db);
var db = mongo.connection;
db.on('error', console.error.bind(console, 'connection error: '));