How to fix the ‘mongoError: Topology was destroyed’ error with Mongoose?

Sometimes, we want to fix the ‘mongoError: Topology was destroyed’ error with Mongoose.

In this article, we’ll look at how to fix the ‘mongoError: Topology was destroyed’ error with Mongoose.

How to fix the ‘mongoError: Topology was destroyed’ error with Mongoose?

To fix the ‘mongoError: Topology was destroyed’ error with Mongoose, we should make sure our connection to the MongoDB server isn’t interrupted.

For instance, we write

const options = {
  server: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 } },
  replset: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 } }
};
mongoose.connect(secrets.db, options);

to call mongoose.connect with the options.

We set the server‘s keepAlive option to 1 to keep the connection alive.

And we set connectTimeoutMS to 30000 milliseconds to extend the connection attempt duration before timing out.

We set the same options for the replica set by setting replset to the same options.

Conclusion

To fix the ‘mongoError: Topology was destroyed’ error with Mongoose, we should make sure our connection to the MongoDB server isn’t interrupted.