Kay
Kay

Reputation: 19680

How to auto reconnect if mongo connection fails in node.js using mongoose?

I have mongodb up and running in a docker container. I stop the container and node returns a MongoError. I restart the container and node continues to throw the same MongoError.

I would like for it to reconnect when there was an issue.

    const uri: string = this.config.db.uri;
    const options = {
            useNewUrlParser: true,
            useCreateIndex: true,
            autoIndex: true,
            autoReconnect: true,
    },

    mongoose.connect(uri, options).then(
        () => {
            this.log.info("MongoDB Successfully Connected On: " + this.config.db.uri);
        },
        (err: any) => {
            this.log.error("MongoDB Error:", err);
            this.log.info("%s MongoDB connection error. Please make sure MongoDB is running.");
            throw err;
        },

    );

How do i setup mongoose to try and auto connect when there is a connection failure to mongodb.

Upvotes: 1

Views: 6224

Answers (1)

Kay
Kay

Reputation: 19680

I found my answer, instead of checking error events and reconnecting like others have suggested. There are some options you can set that will handle auto-reconnect.

Here are the set of mongoose options i am now using.

const options = {
            useNewUrlParser: true,
            useCreateIndex: true,
            autoIndex: true,
            reconnectTries: Number.MAX_VALUE, // Never stop trying to reconnect
            reconnectInterval: 500, // Reconnect every 500ms
            bufferMaxEntries: 0,
            connectTimeoutMS: 10000, // Give up initial connection after 10 seconds
            socketTimeoutMS: 45000, // Close sockets after 45 seconds of inactivity
        }

You can test it works by starting and stoping mongodb in a container and checking your node application.

For furuther information refer to this part of the documentation. https://mongoosejs.com/docs/connections.html#options

Upvotes: 7

Related Questions