如何检查Node.js中的MongoDB连接是否仍然存在 [英] How to check if MongoDB connection is alive in Node.js

查看:81
本文介绍了如何检查Node.js中的MongoDB连接是否仍然存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以MongoDB为后端的应用程序.启动应用程序后,我将建立连接并稍后在请求时使用它.

I have an app with MongoDB as backend. When the app is started, I set up the connection and use it later on requests.

但是,如果在此期间我的数据库连接失败(例如mongod崩溃),我该如何在请求时间进行检查?

But if in the mean time my db conncetion fails (ie. mongod crashes), how can I check that on the request time?

要澄清一下:

  • 当前我有一个"api.js",它可以db.once('open', function../* setup */)
  • 根据要求,我执行db.find(conditions, function(err, res) { if (err) ...else ...}).
  • 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 ...}).

我想做的是在db.find()子句之前检查连接是否处于活动状态.因此,如果连接断开,我可以尝试重新启动数据库连接.

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.我知道,我可能应该设置某种连接池或类似的连接池,而不是一直保持连接处于活动状态,但是现在它是按原样设置的.

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.

推荐答案

您可以使用事件将其作为回调进行处理.
也许有您的全局变量可以识别它是否未连接.

You can use event to handle it as callback.
And maybe have your global variable that will identify that it is not connected.

您可以有一个单独的db.js文件,该文件将作为模块运行.并且您可以具有从中获取收藏的功能.

You can have separate db.js file, that will behave as module. And you can have function to get collection from it.

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

对不起,刚刚注意到您使用猫鼬,这可能会有所不同.

Sorry, just noticed you are using Mongoose, which can be different slightly.

这篇关于如何检查Node.js中的MongoDB连接是否仍然存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆