首页 > 解决方案 > MongooseServerSelectionError 连接超时后重试

问题描述

我希望我的 nodejs 应用程序在与猫鼬的初始连接失败后重试。我在我的应用程序中连接到两个单独的数据库。以下是供您参考的代码片段。

function makeNewConnection(uri) {

    const db = mongoose.createConnection(uri, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        serverSelectionTimeoutMS: 180000
    });

    db.on('error', async function (error) {
        console.log(`MongoDB :: connection ${this.name} ${JSON.stringify(error)}`);
        db.close().catch(() => console.log(`MongoDB :: failed to close connection ${this.name}`));
    });

    db.on('connected', function () {
        mongoose.set('debug', false);
        console.log(`MongoDB :: connected ${this.name}`);
    });

    db.on('disconnected', function () {
        console.log(`MongoDB :: disconnected ${this.name}`);
    });
    return db;
}

const localDBconnection = makeNewConnection(localDB);
const serverDBConnection = makeNewConnection(serverDB); 

localDB 和 serverDB 是我的两个连接 uri。如果我超时重试,那么它找不到模型实例。有人可以建议一个干净的方法来做到这一点。

标签: node.jsmongodbmongoose

解决方案


推荐阅读