【问题标题】:How to auto reconnect if mongo connection fails in node.js using mongoose?如果使用猫鼬在node.js中mongo连接失败,如何自动重新连接?
【发布时间】:2019-08-22 19:58:21
【问题描述】:

我已经在 docker 容器中启动并运行了 mongodb。我停止容器,节点返回 MongoError。我重新启动容器,节点继续抛出相同的 MongoError。

我希望它在出现问题时重新连接。

    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;
        },

    );

我如何设置 mongoose 在 mongodb 连接失败时尝试自动连接。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    我找到了答案,而不是像其他人建议的那样检查错误事件并重新连接。您可以设置一些选项来处理自动重新连接。

    这是我现在使用的一组猫鼬选项。

    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
            }
    

    您可以通过在容器中启动和停止 mongodb 并检查您的节点应用程序来测试它是否有效。

    有关更多信息,请参阅文档的这一部分。 https://mongoosejs.com/docs/connections.html#options

    【讨论】:

    • 警告:如果初始连接失败,这将不起作用,只有初始连接成功然后断开连接。
    猜你喜欢
    • 1970-01-01
    • 2021-10-25
    • 2013-04-20
    • 1970-01-01
    • 1970-01-01
    • 2014-12-03
    • 1970-01-01
    • 2018-07-24
    • 2014-12-28
    相关资源
    最近更新 更多