如何在汇集时立即检测到mongodb err和响应?

时间:2017-06-14 01:03:33

标签: node.js mongodb

这是连接池代码。

var express = require('express');
var mongodb = require('mongodb');
var app = express();

var MongoClient = require('mongodb').MongoClient;
var db;

// Initialize connection once
MongoClient.connect("mongodb://localhost:27017/integration_test", function(err, database) {
  if(err) throw err;

  db = database;

  // Start the application after the database connection is ready
  app.listen(3000);
  console.log("Listening on port 3000");
});

// Reuse database object in request handlers
app.get("/", function(req, res) {
  db.collection("replicaset_mongo_client_collection").find({}, function(err, docs) {
    docs.each(function(err, doc) {
      if(doc) {
        console.log(doc);
      }
      else {
        res.end();
      }
    });
  });
});

我的问题是服务器是否成功启动但是在运行期间与MongoDB的连接丢失(或关闭)。

如何在申请我的服务器时发现这一点? 没有回应像'间隔1000毫秒30次尝试后未能重新连接'

解决

// Added global value to flag event
var MongoPool = true;

// Initialize connection once
MongoClient.connect("mongodb://localhost:27017/integration_test", function(err, database) {
  if(err) throw err;

  db = database;

  // Listen event
  db.on('close', function () {
   console.log('Conection closed');
   MongoPool = false;
  });

  // Start the application after the database connection is ready
  app.listen(3000);
  console.log("Listening on port 3000");
});

// Reuse database object in request handlers
app.get("/", function(req, res) {
  if(MongoPool){
     // query
  } else {
     // response immediatly :)
  };
});

或者您可以通过以下链接修改MongoDB连接重试 Reliably reconnect to MongoDB

1 个答案:

答案 0 :(得分:0)

errordb.on('close', function () { console.log('Conection closed'); }); db.on('error', function (e) { console.log('Error: ', e); });

等事件使用侦听器
MongoCliente.connect

More information in the official documentation

在您的代码中,它将位于var express = require('express'); var mongodb = require('mongodb'); var app = express(); var MongoClient = require('mongodb').MongoClient; var db; // Initialize connection once MongoClient.connect("mongodb://localhost:27017/integration_test", function(err, database) { if(err) throw err; db = database; // Start the application after the database connection is ready app.listen(3000); console.log("Listening on port 3000"); db.on('close', function () { console.log('Conection closed'); }); db.on('error', function (e) { console.log('Error: ', e); }); }); 回调内:

{{1}}