You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何手动重新连接Mongoose次级连接而不创建新连接?

问题

应用有两个Mongoose连接:一个使用mongoose.connect()的默认连接,另一个使用mongoose.createConnection()创建的次级连接。应用运行数月无异常,但近两周MongoDB连接意外中断。为默认连接添加了重连函数,通过再次调用mongoose.connect()实现重连,效果良好,Mongoose连接事件也能正常触发。但次级连接存在问题:该连接导出了PhoneModel,若尝试修改重连函数,将mongoose.connect()替换为secondaryConnection = mongoose.createConnection(),会创建全新连接,而应用仍会使用旧连接的模型,且新连接的事件无法正常工作。

现有代码示例:

默认连接及重连逻辑:

let reconnectAttempt = 0;

const reconnect = () => {
  try {
    reconnectAttempt++;

    if (mongoose.connection.readyState === 0) {
      console.log(
        `Trying to reconnect. Attempt: ${reconnectAttempt}`,
      );

      mongoose.connect(connectionString, mongooseOptions);

      if (reconnectAttempt >= 5) {
        console.log(`Reconnect failed`);
      } else {
        reconnect();
      }
    }
  } catch (error) {
    console.log(error);
  }
};

const connectMongoPrimary = () => {
  try {
    mongoose.set("strictQuery", true);
    mongoose.connect(connectionString, mongooseOptions);
  } catch (error) {
    console.log(error);
  }
};

mongoose.connection.on("disconnected", () => {
  reconnect();
});

次级连接代码:

secondaryConnection = mongoose.createConnection(
  connectionString,
  mongooseOptions,
);

const PhoneModel = secondaryConnection.model("Phone", PhoneSchema);

export { PhoneModel };

请问如何手动重新连接secondaryConnection而不创建新连接?

解决方案

无需重新创建createConnection实例,调用现有连接实例的openUri()方法即可重新建立连接,同时保证模型始终绑定到同一连接实例上。

步骤1:为次级连接封装重连函数

利用现有连接实例的openUri()方法实现重连,避免创建新连接:

let secondaryReconnectAttempt = 0;

const reconnectSecondary = () => {
  try {
    secondaryReconnectAttempt++;
    if (secondaryConnection.readyState === 0) {
      console.log(`Secondary connection trying to reconnect. Attempt: ${secondaryReconnectAttempt}`);
      // 复用现有连接实例执行重连
      secondaryConnection.openUri(connectionString, mongooseOptions);
      
      if (secondaryReconnectAttempt >= 5) {
        console.log(`Secondary reconnect failed after 5 attempts`);
      } else {
        // 添加延迟避免频繁重试
        setTimeout(reconnectSecondary, 2000);
      }
    }
  } catch (error) {
    console.error(`Secondary reconnect error:`, error);
    setTimeout(reconnectSecondary, 2000);
  }
};

步骤2:绑定次级连接的断开事件

在创建次级连接后,绑定disconnected事件触发重连逻辑:

secondaryConnection = mongoose.createConnection(
  connectionString,
  mongooseOptions,
);

// 断开时触发重连,同时重置重试计数器
secondaryConnection.on("disconnected", () => {
  console.log("Secondary MongoDB connection disconnected");
  secondaryReconnectAttempt = 0;
  reconnectSecondary();
});

// 可选:监听连接成功事件,确认重连状态
secondaryConnection.on("connected", () => {
  console.log("Secondary MongoDB connection successfully connected");
});

const PhoneModel = secondaryConnection.model("Phone", PhoneSchema);

export { PhoneModel, secondaryConnection };

关键说明

  • secondaryConnection.openUri():该方法复用现有连接实例重建连接,模型会自动关联到重连后的实例,无需重新定义模型。
  • 重置重试计数器:避免之前的失败次数干扰新的重连周期。
  • 延迟重试:用setTimeout添加间隔,避免同步阻塞和数据库压力过大。
  • 保留原连接实例:始终使用同一个secondaryConnection,确保应用中所有使用PhoneModel的代码都能关联到重连后的连接。

内容的提问来源于stack exchange,提问作者Fernando

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 20:56:21