繁体   English   中英

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

[英]How to check if mongos connection still alive in Node.JS?

假设我们有一个连接到 Mongos 进程的 Node.JS 应用程序。 但突然间 Mongos 失败了。 我们的应用程序现在如何呢?

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

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

IE

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

或者,如果您使用 3rd 方 mongo 管理器,例如 mongoose,您可以在全局范围内执行以下操作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM