Normally, the ‘MongoDB error topology was destroyed’ error occurs if the node server’s connection to the MongoDB instance was interrupted while it was trying to write to it. Or if the mongo driver drops the connection for any reason.
Another reason could be mongoose disconnecting before mongo document indexes are created
Here at Bobcares, we have seen several such MongoDB errors as part of our Server Management Services for web hosts and online service providers.
Today, let us see how our Support Engineers resolve this MongoDB error message.
How we resolve the error ‘MongoDB error topology was destroyed’
Recently, one of our customers approached us with a MongoDB error message. He told that suddenly the node started crapping out errors with the message “MongoDB error: Topology was destroyed”.
Now let’s take a look at how our Support Engineers resolve this error message.
Here, we found that the mongo driver was dropping the connection. So, we can increase the retry time value.
By default, the mongoose will try to reconnect for 30 seconds and then stop retrying. After that, it throws errors forever until we restart it.
We change this by editing the below fields.
mongoose.connect(MONGO_URL, { server: { // sets how many times to try reconnecting reconnectTries: Number.MAX_VALUE, // sets the delay between every retry (milliseconds) reconnectInterval: 1000 } } );
This instantly fixes the error for the customer.
Another reason could be mongoose disconnecting before the creation of mongo document indexes.
In order to make sure all models have their indexes built before disconnecting, we can make the below changes:
await Promise.all(mongoose.modelNames().map(model => mongoose.model(model).ensureIndexes())); await mongoose.disconnect();
This must resolve the error.
[Need any further assistance in fixing MongoDB errors? – We are here to help you.]
Conclusion
In short, this error can occur due to many reasons that include interruption of the node server’s connection to the MongoDB instance while it was trying to write to it. If the mongo driver drops the connection for any reason. Another reason could be mongoose disconnecting before the creation of mongo document indexes. Today, we saw how our Support Engineers fix this MongoDB error.
0 Comments