如果使用 mongoose 在 node.js 中 mongo 连接失败,如何自动重新连接?

Kay*_*Kay 0 mongoose mongodb node.js

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

    );
Run Code Online (Sandbox Code Playgroud)

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

Kay*_*Kay 5

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

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

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
        }
Run Code Online (Sandbox Code Playgroud)

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

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