Prakash Kumar
Prakash Kumar

Reputation: 879

When mongodb server is down how to catch the error while running mongoose query

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

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

Upvotes: 1

Views: 2646

Answers (1)

Tal Avissar
Tal Avissar

Reputation: 10314

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

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: Emitted when connection.{open,openSet}() is executed on this connection.

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

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

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

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

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

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

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

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

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

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.

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

Upvotes: 3

Related Questions