MongoDB Reconnect

This is a demo repository which shows how to reconnect with MongoDB Server with NodeJS.

MongooseJS has awesome event handling. With the help of disconnect event, we will get know that connection has broken with MongoDB Server so we can try to reconnect with MongoDB. Below is the sample/demo app, which will try to reconnect with(Here we capture MongoDB disconnect event and try to reconnect with) MongoDB. And as soon as MongoDB Server will up again, it will automatically connect to MongoDB without restarting the NodeJS Server.

 * Created by Amit Thakkar on 9/21/15.
(function (require) {
    'use strict';
    var mongoose = require('mongoose');
    var mongoURL = 'mongodb://localhost/test';
    var db;
    var reconnectTimeout = 5000;
    var connectWithRetry = function(cb) {
        mongoose.connect(mongoURL, function(error) {
            if (error) {
                console.error('Failed to connect to MongoDB on startup', error);
            } else {
      'Connected with MongoDB Server');
        db = mongoose.connection;
        cb && cb();
    connectWithRetry(function() {
        db.on('error', function (error) {
            console.error('Mongoose Error: ', error);
        db.on('connected', function () {
  'Mongoose Connected to ', mongoURL);
        db.once('open', function () {
  'Mongoose Connection Open with MongoDB Server on ', mongoURL);
        db.on('disconnected', function () {
  'Mongoose connection disconnected');
            setTimeout(connectWithRetry, reconnectTimeout);

Reconnect interval is 5sec here.

Follow Me




More Blogs By Me