'Handling Database reconnections with MongoDB Native Driver in Node.JS
With mongoose one can simply handle reconnections via connection-options:
let dbOptions = {
dbName: process.env.MONGO_DATABASE_NAME,
autoReconnect: true,
reconnectInterval: 1000,
reconnectTries: 10,
};
mongoose.connect(process.env.MONGO_URI, dbOptions);
// Create connection object.
const db = mongoose.connection;
In the native MongoDB driver (version 4.4) there are no similar connection options available: https://mongodb.github.io/node-mongodb-native/4.4/interfaces/MongoClientOptions.html
What is the easiest way to handle database reconnections in case of a major error?
Solution 1:[1]
Wherever you've got the mongoose connection snippet from, it's outdated.
The autoReconnect and auto_reconnect options were a thing in Nodejs native driver before v4.0, and mongoose just proxied these options to the driver.
This is the documentation for the driver 3.7 with "autoReconnect" still there: http://mongodb.github.io/node-mongodb-native/3.7/api/global.html#MongoClientOptions and this is the commit where it's been removed: https://github.com/mongodb/node-mongodb-native/commit/e3cd9e684aea99be0430d856d6299e65258bb4c3#diff-f005e84d9066ef889099ec2bd907abf7900f76da67603e4130e1c92fac92533dL90
The option was "True" by default with a strong note to do not change this value unless you know exactly why you need to disable it.
v4 introduced many changes to the driver - refactoring to typescript, architectural changes, you can see it from the commit, right. One of the changes affected connection logic and pool management. There is no option to disable reconnection anymore. It's always reconnects regardless how you connect directly or via mongoose.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alex Blex |
