How to Handle Lost Connection to Mongodb from Nodejs?

Handling lost connections to MongoDB in a Node.js application is crucial for maintaining application reliability and data integrity. However, network issues, database server crashes, or other unexpected events can cause the connection to be lost. This article will guide you through different approaches to handle them, and provide a step-by-step guide to creating a robust application that gracefully manages lost connections.

These are the following approaches:

Table of Content

  • Using Mongoose
  • Using MongoDB Native Driver
  • Using Event Listeners
  • Using a Function for Retry Logic

Using Mongoose

In this approach, we utilize Mongoose to establish connections to MongoDB in a Node.js application and for reconnections. The reconnection logic in this method listens for the 'disconnected' event on the MongoDB connection. Upon detecting disconnection, it initiates a reconnection attempt by invoking mongoose.connect with the same connection parameters. This ensures that if the connection to the MongoDB database is lost, the application will automatically try to reconnect.

Node
const mongoose = require('mongoose');

mongoose.connect(
'mongodb://localhost:27017/mydatabase', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

const db = mongoose.connection;

db.on('error', console.error.bind(console,
              'connection error:'));
db.once('open', function() {
  console.log('Connected to MongoDB');
});

// Handling reconnection
db.on('disconnected', () => {
  console.log('MongoDB disconnected! Attempting to reconnect...');
  mongoose.connect(
'mongodb://localhost:27017/mydatabase', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  });
});

Using MongoDB Native Driver

The MongoDB Native Driver provides low-level access to MongoDB, offering more control over the connection. In this method, we utilize MongoClient for connection establishment. When the ‘close’ event triggers on the MongoDB client instance, indicating an unexpected disconnection from the MongoDB server, the application initiates a reconnection attempt by invoking the connect function. This function employs await client.connect() to establish a new connection to the MongoDB server.

Node
const { MongoClient } = require('mongodb');

const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

async function connect() {
  try {
    await client.connect();
    console.log('Connected to MongoDB');
  } catch (err) {
    console.error('Failed to connect', err);
  }
}

client.on('close', () => {
  console.log('MongoDB connection lost. Reconnecting...');
  connect();
});

connect();

Using Event Listeners

Event listeners allow you to handle various MongoDB connection events such as connected, disconnected, reconnected, and error.

This method establishes a MongoDB connection using Mongoose and implements reconnection logic. If the connection is lost, it retries the connection every 5 seconds using setTimeout. Event listeners are set up to log when the connection is established, lost, or reestablished, as well as to handle any connection errors.

Node
const mongoose = require('mongoose');

mongoose.connect(
'mongodb://localhost:27017/mydatabase', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

const db = mongoose.connection;

db.on('connected', () => {
  console.log('MongoDB connected');
});

db.on('disconnected', () => {
  console.log('MongoDB disconnected');
  setTimeout(() => {
    mongoose.connect(
'mongodb://localhost:27017/mydatabase', {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });
  }, 5000); // Retry connection after 5 seconds
});

db.on('reconnected', () => {
  console.log('MongoDB reconnected');
});

db.on('error', (error) => {
  console.error('MongoDB connection error:', error);
});

Using a Function for Retry Logic

In this method, we establishes a MongoDB connection using Mongoose and implements retry logic for reconnections. The connectWithRetry function attempts to connect to the MongoDB database, and if the connection fails, it retries every 5 seconds. Event listeners are set up to log when the connection is established, lost, or reestablished.

Node
const mongoose = require('mongoose');

const connectWithRetry = () => {
  console.log('MongoDB connection with retry');
  return mongoose.connect(
'mongodb://localhost:27017/mydatabase', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  }).catch(() => {});
};

mongoose.connection.on('connected', () => {
  console.log('MongoDB is connected');
});

mongoose.connection.on('error', (err) => {
  console.log(`MongoDB connection error: ${err}`);
  setTimeout(connectWithRetry, 5000);
});

mongoose.connection.on('disconnected', () => {
  console.log('MongoDB is disconnected');
  setTimeout(connectWithRetry, 5000);
});
connectWithRetry();


Contact Us