当mongodb服务器关闭时,如何在运行mongoose查询时捕获错误 [英] When mongodb server is down how to catch the error while running mongoose query

查看:58
本文介绍了当mongodb服务器关闭时,如何在运行mongoose查询时捕获错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用mongoose将mongoDB连接到node.js,现在我在查询下面写了

I am using mongoose for connecting node.js with mongoDB, now i wrote below query

var trans = new transmodel({method: method, trans_id: r});
  trans.save(function(err) {
      if (err) {
            console.error("Razor_pay_webhook Error 4 err: " + err);
            res.write('statusCode: 200');
            res.end();
     } else {
        res.write('statusCode: 400');
        res.end();
     }
  });

我以为当我的mongodb集群关闭时,在执行以上mongoose查询时我会得到"err",但是当我在mongo集群关闭时运行以上查询时,没有任何反应(未调用err).任何人都可以告诉我如果我的mongodb服务器在查询范围内时如何捕获错误.同样,为了再次与群集重新连接,我已经设置了以下参数,但是我的节点服务器没有尝试与mongodb服务器重新连接,我不知道出了什么问题.

I thought when my mongodb cluster will be down then i will get 'err' while executing above mongoose query, but when i ran above query while my mongo cluster was down nothing happened(No err was called). Can anyone please tell me how can i catch the error if my mongodb server is down inside my query. Also for reconnecting again with my cluster i have set below parameters but my node server is not trying to reconnect again with my mongodb server i don't know what's going wrong.

var mongoose = require('mongoose');
    var config = require('./config/database.js');
    var DB_URL = config.db.url;

    mongoose.connection.on("connected", function(ref) {
        console.log("Connected to " + " DB!");
    });

    mongoose.connection.on("error", function(err) {
        console.error('Failed to connect to DB ' + ' on startup ', err);
        if (err) {
            return next(err);
        }
    });

    mongoose.connection.on('disconnected', function(err) {
        console.log('Mongoose default connection to DB :' + ' disconnected');
        if (err) {
            return next(err);
        }
    });

    var gracefulExit = function() { 
        mongoose.connection.close(function () {
            console.log('Mongoose default connection with DB :'  + ' is disconnected through app termination');
            process.exit(0);
        });
    }

    process.on('SIGINT', gracefulExit).on('SIGTERM', gracefulExit);

    exports.con_close = function () {
        console.log('Mongoose connection disconnected');
        mongoose.connection.close();
    }

    var options = {
        server: {
            socketOptions: {
                keepAlive: 1000,
                connectTimeoutMS: 30000
            }
        },
        replset: { 
            rs_name: 'replicaset',
            auto_reconnect:true,
            socketOptions: {
                keepAlive: 1000, // doubt about it
                connectTimeoutMS: 30000
            } 
        },
        user: 'root',
        pass: 'G3saGT2Y',
        auth: {
            authdb: 'admin'
        }
    }

    mongoose.connect(DB_URL, options, function(err) {
        console.log('ho rha hai');
        if (err) {
            console.log('error connection to mongo server!');
            console.log(err);
        }
    });

推荐答案

您正在使用猫鼬,当数据库关闭,数据库重新连接并再次启动时,它将发出事件(EventEmitter模式).

You are using mongoose, it emits events (the EventEmitter pattern) when the database is down and when the database is reconnecting and up again.

从猫鼬代码中找到

在这里,我们可以看到库数据库连接-

from mongoose code found here we can see that the library db connection - connection.js

具有以下发出的事件: * @param {Mongoose}建立一个猫鼬实例 * @inherits NodeJS EventEmitter

has the following events that are emitted: * @param {Mongoose} base a mongoose instance * @inherits NodeJS EventEmitter

http://nodejs.org/api/events.html#events_class_events_eventemitter * @event connecting:在此连接上执行connection.{open,openSet}()时发出.

http://nodejs.org/api/events.html#events_class_events_eventemitter * @event connecting: Emitted when connection.{open,openSet}() is executed on this connection.

  • @event connected:此连接成功连接到数据库时发出.在reconnected场景中可能被发射多次次.

  • @event connected: Emitted when this connection successfully connects to the db. May be emitted multiple times in reconnected scenarios.

@event open:在所有这些连接模型上执行connectedonOpen后发出.

@event open: Emitted after we connected and onOpen is executed on all of this connections models.

@event disconnecting:在执行connection.close()时发出.

@event disconnecting: Emitted when connection.close() was executed.

@event disconnected:与数据库断开连接后发出.

@event disconnected: Emitted after getting disconnected from the db.

@event close:在所有这些连接模型上执行disconnectedonClose后发出.

@event close: Emitted after we disconnected and onClose executed on all of this connections models.

@event reconnected:在我们connected和随后的disconnected之后发出,然后成功进行另一个成功连接后发出.

@event reconnected: Emitted after we connected and subsequently disconnected, followed by successfully another successfull connection.

@event error:此连接上发生错误时触发.

@event error: Emitted when an error occurs on this connection.

@event fullsetup:在副本集方案中,当处于主级且位于 连接字符串中指定的至少一个seconaries.

@event fullsetup: Emitted in a replica-set scenario, when primary and at least one seconaries specified in the connection string are connected.

@event all:当连接字符串中指定的所有节点均已连接时,在副本集方案中发出.

@event all: Emitted in a replica-set scenario, when all nodes specified in the connection string are connected.

当数据库关闭时,您将收到两个事件: 1.断开 2.错误(驱动程序遇到的错误)

When the database is down you will receive two events: 1. disconnected 2. error (the error that driver encountered)

当数据库再次启动时,您将收到重新连接事件.

When the database is up again you will receive the reconnect event.

因此,您无需尝试捕获错误,而应该听这些事件.

So you don't need to try catch the error rather you should listen to these events.

有关连接失败和重新连接的更多有用信息,请参见此处.

More helpful information about connection failures and reconnecting can be found here.

本文介绍了如何根据您的设置使用和配置autoReconnect和bufferMaxEntries.

This article explain how to use and configure the autoReconnect and the bufferMaxEntries according to your settings.

这篇关于当mongodb服务器关闭时,如何在运行mongoose查询时捕获错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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