簡體   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