Sling Academy
Home/Node.js/Fix mongoError: Topology was destroyed – Mongoose

Fix mongoError: Topology was destroyed – Mongoose

Last updated: December 30, 2023

Understanding the Topology Destroyed Error

When you encounter the MongoError: Topology was destroyed message in your Node.js application using Mongoose, it indicates that an operation was attempted on a MongoDB connection that was closed or no longer accessible. This could occur for several reasons, including idle timeouts, network issues, or explicit connection closures in your code that precede database operations.

Troubleshooting the Error

It’s essential to check for any intentional connection closures in your code – any call to mongoose.disconnect() or connection.close() that may occur before your operations complete. Adjusting these calls can prevent operations from being attempted on a closed connection.

If connections are being closed due to idle timeouts or transient network problems, consider implementing a robust connection and reconnection strategy. You can configure Mongoose to handle reconnections by setting the autoReconnect flag and specifying reconnectTries and reconnectInterval options.

Configuring Mongoose for Reconnection

Here’s an example configuring Mongoose to handle disconnections gracefully:

const mongoose = require('mongoose');

const options = {
  autoReconnect: true,
  reconnectTries: Number.MAX_VALUE,
  reconnectInterval: 1000
};

async function connectWithRetry() {
  try {
    await mongoose.connect('mongodb://localhost:27017/yourdb', options);
    console.log('MongoDB is connected');
  } catch (err) {
    console.log('MongoDB connection unsuccessful, retry after 5 seconds.');
    setTimeout(connectWithRetry, 5000);
  }
}

connectWithRetry();

By using an async function that employs a delay before retrying, you can attempt to establish a connection repeatedly when it fails. Additionally, by monitoring the connected, disconnected, and reconnectFailed events using listeners, you can create finer control and logging on your connection status:

mongoose.connection.on('connected', () => {
  console.log('Mongoose connected to the database');
});

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

mongoose.connection.on('disconnected', () => {
  console.log('Mongoose disconnected');
});

process.on('SIGINT', async () => {
  await mongoose.connection.close();
  console.log('MongoDB connection closed due to app termination');
  process.exit(0);
});

The proper management of events and connection life cycle goes a long way in mitigating the Topology was destroyed errors. However, if the issue persists it may be due to deeper networking issues or a bug within the version of the MongoDB driver you are using. Ensure you are running the latest version of the Mongoose and MongoDB driver compatible with your MongoDB server version.

Next Article: Mongoose: How to efficiently work with very large collections

Previous Article: Using Regular Expressions in Mongoose Queries

Series: Mongoose.js Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates