MongoDB持续出现连接超时错误,同款代码昨日可正常连接
MongoDB连接超时(ReplicaSetNoPrimary)排查方案
针对你遇到的MongoServerSelectionError: connection <monitor> to 18.231.18.253:27017 closed且提示ReplicaSetNoPrimary的问题,结合代码昨日正常运行的情况,按以下步骤排查:
检查MongoDB Atlas IP白名单
当前设备公网IP可能因重启路由器、切换网络等原因发生变化,不在Atlas白名单内。登录MongoDB Atlas控制台,进入对应集群的「Network Access」页面,添加当前设备公网IP,或临时设置0.0.0.0/0(仅测试用,生产环境禁用)后重试。排查网络环境限制
公司内网、校园网等环境可能屏蔽27017端口,或存在防火墙、代理拦截出站连接。切换到手机热点等不受限网络测试,或检查本地防火墙是否允许Node.js访问外部网络。查看MongoDB Atlas集群状态
Atlas集群可能临时维护或出现故障,导致无法找到主节点。登录Atlas控制台,查看集群「Overview」页面,确认是否有运行异常或告警。调整连接字符串参数
增加超时参数延长连接等待时间,同时确保用户名密码已正确替换:const uri = "mongodb+srv://<MyUser>:<MyPassword>@cluster0.ot7abmk.mongodb.net/?retryWrites=true&w=majority&connectTimeoutMS=30000&socketTimeoutMS=30000"升级MongoDB驱动版本
mongodb@5.0可能存在已知连接兼容性问题,尝试升级到同大版本的稳定版:npm install mongodb@5.9 --save(注意:5.x驱动要求Node.js版本≥14)
完善错误捕获
在调用run函数时添加错误捕获,便于更清晰定位问题:run().catch(err => console.error("连接失败:", err));
你的代码片段
const uri = "mongodb+srv://<MyUser>:<MyPassword>@cluster0.ot7abmk.mongodb.net/?retryWrites=true&w=majority" const client = new MongoClient(uri); async function run(){ try { await client.connect(); console.log("Connected successfully to server"); } finally { await client.close(); } }
package.json配置
{ "name": "controle-de-gastos-full-stack", "version": "1.0.0", "description": "", "main": "index.js", "type": "module", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/G4rutti/controle-de-gastos-full-stack.git" }, "keywords": [], "author": "", "license": "ISC", "bugs": { "url": "https://github.com/G4rutti/controle-de-gastos-full-stack/issues" }, "homepage": "https://github.com/G4rutti/controle-de-gastos-full-stack#readme", "dependencies": { "mongodb": "5.0" } }
错误信息
MongoServerSelectionError: connection <monitor> to 18.231.18.253:27017 closed at Timeout._onTimeout (MyDir) at listOnTimeout (node:internal/timers:564:17) at process.processTimers (node:internal/timers:507:7) { reason: TopologyDescription { type: 'ReplicaSetNoPrimary', servers: Map(3) { 'ac-kac6ni2-shard-00-02.ot7abmk.mongodb.net:27017' => [ServerDescription], 'ac-kac6ni2-shard-00-00.ot7abmk.mongodb.net:27017' => [ServerDescription], 'ac-kac6ni2-shard-00-01.ot7abmk.mongodb.net:27017' => [ServerDescription] }, stale: false, compatible: true, heartbeatFrequencyMS: 10000, localThresholdMS: 15, setName: 'atlas-hqwzt1-shard-0', maxElectionId: null, maxSetVersion: null, commonWireVersion: 0, logicalSessionTimeoutMinutes: null }, code: undefined, [Symbol(errorLabels)]: Set(0) {} }
内容的提问来源于stack exchange,提问作者G4rutti
相关产品推荐
相关产品推荐

