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

MongoServerSelectionError随机触发致应用崩溃问题求助

随机出现MongoServerSelectionError导致应用崩溃问题求助

我正试图解决一个困扰我一段时间的问题:大部分数据库操作可正常执行,但会随机出现MongoServerSelectionError导致应用崩溃。该问题在本地和生产环境均会发生,且无法稳定复现。

依赖版本

"mongodb": "^6.5.0",
"mongoose": "^8.3.1",
"@auth/mongodb-adapter": "^2.6.0" // 不确定是否与问题相关

Vercel日志中的完整错误信息

Unhandled Rejection: MongoServerSelectionError: Server selection timed out after 30000 ms
at EventTarget.<anonymous> (/var/task/node_modules/.pnpm/mongodb@6.5.0/node_modules/mongodb/lib/sdam/topology.js:289:34)
at [nodejs.internal.kHybridDispatch] (node:internal/event_target:786:20)
at EventTarget.dispatchEvent (node:internal/event_target:721:26)
at abortSignal (node:internal/abort_controller:369:10)
at TimeoutController.abort (node:internal/abort_controller:403:5)
at Timeout.<anonymous> (/var/task/node_modules/.pnpm/mongodb@6.5.0/node_modules/mongodb/lib/utils.js:976:92)
at listOnTimeout (node:internal/timers:569:17)
at process.processTimers (node:internal/timers:512:7) {
reason: TopologyDescription {
type: 'ReplicaSetNoPrimary',
servers: Map(3) {
'ac-ygz1cvo-shard-00-00.frnyejo.mongodb.net:27017' => [ServerDescription],
'ac-ygz1cvo-shard-00-01.frnyejo.mongodb.net:27017' => [ServerDescription],
'ac-ygz1cvo-shard-00-02.frnyejo.mongodb.net:27017' => [ServerDescription]
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: 'atlas-k31dqm-shard-0',
maxElectionId: null,
maxSetVersion: null,
commonWireVersion: 0,
logicalSessionTimeoutMinutes: null
},
code: undefined,
[Symbol(errorLabels)]: Set(0) {}
}

MongoDB客户端配置文件

import { MongoClient } from "mongodb";

const uri = process.env.MONGODB_URI;
const options = {};

let client;
let clientPromise;

if (!uri) {
  console.error("⚠️ MONGODB_URI missing from .env");
} else {
  try {
    client = new MongoClient(uri, options);
    clientPromise = client.connect();
  } catch (err) {
    console.error("MongoDB client error: " + err);
  }
}

export default clientPromise;

Mongoose连接配置文件

import mongoose from "mongoose";

let mongooseConnection = null;

const connectMongo = async () => {
  if (mongooseConnection) {
    return mongooseConnection;
  }

  if (!process.env.MONGODB_URI) {
    throw new Error("MONGODB_URI is not defined");
  }

  try {
    const db = await mongoose.connect(process.env.MONGODB_URI, {
      serverSelectionTimeoutMS: 5000,
      socketTimeoutMS: 45000,
      heartbeatFrequencyMS: 10000,
    });
    mongooseConnection = db;
    return db;
  } catch (e) {
    console.error("Mongoose connection error: " + e);
    throw e;
  }
};

export default connectMongo;

有Mongo Compass监控页截图可供参考。

请问是否有人遇到过该问题并找到了解决方案?我已尝试调整连接参数,但未取得成效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 17:14:52