MongoServerSelectionError(ReplicaSetNoPrimary)连接故障求助
连接MongoDB Atlas突然失败:MongoServerSelectionError: getaddrinfo ENOTFOUND
错误信息
MongoServerSelectionError: getaddrinfo ENOTFOUND ac-8q8dm3y-shard-00-00.5ldtt3z.mongodb.net at Timeout._onTimeout (/home/runner/Bojji/node_modules/mongodb/lib/sdam/topology.js:292:38) at listOnTimeout (node:internal/timers:557:17) { reason: TopologyDescription { type: 'ReplicaSetNoPrimary', servers: Map(3) { 'primary' => [ServerDescription], 'secondary' => [ServerDescription], 'secondary' => [ServerDescription] }, stale: false, compatible: true, heartbeatFrequencyMS: 10000, localThresholdMS: 15, setName: 'atlas-q5c7wq-shard-0', maxElectionId: null, maxSetVersion: null, commonWireVersion: 0, logicalSessionTimeoutMinutes: null }, code: undefined, [Symbol(errorLabels)]: Set(0) {} }
此前连接正常运行2周,4小时前突然失效。
连接字符串
mongodb+srv://myusername:mypassword@cluster0.5ldtt3z.mongodb.net/bot?retryWrites=true&w=majority
连接代码
const { MongoClient } = require("mongodb"); const mySecret = process.env['dbToken']; let dbConnection; module.exports = { connectToDb: (cb) => { MongoClient.connect(mySecret) .then((client) => { dbConnection = client.db(); return cb(); }) .catch(err => { console.log(err); return cb(err); }) }, getDb: () => dbConnection }
已尝试的无效解决方案
- 使用Google DNS(本地Windows环境)
- 将IP(包括0.0.0.0/0)添加至MongoDB白名单
- 禁用Windows Defender
- 更新Mongo用户密码
- 重启路由器
- 在防火墙中放行出站端口27015-27017(本地Windows环境)
环境信息
- MongoDB集群版本:5.0.14
- MongoDB集群层级:M0 Sandbox(通用型)
- MongoDB类型:副本集 - 3节点
- MongoDB包版本:4.13.0
- 运行环境:Replit(本地操作系统为Windows 11)
可能的解决方向
1. 针对Replit环境的DNS解析问题
你的操作大多针对本地Windows环境,但代码运行在Replit云端环境,本地网络设置不影响Replit。在Replit的Shell中执行以下命令测试DNS解析:
nslookup ac-8q8dm3y-shard-00-00.5ldtt3z.mongodb.net
如果无法解析,可在Replit项目的replit.nix文件中添加DNS配置,例如:
{ pkgs }: { deps = [ pkgs.nodejs pkgs.dnsmasq ]; env = { DNS_NAMESERVERS = "8.8.8.8,8.8.4.4"; }; }
修改后保存,Replit会自动重建环境。
2. 替换为非SRV格式的连接字符串
SRV连接字符串依赖DNS解析获取分片节点地址,若Replit环境存在解析问题,可在MongoDB Atlas控制台获取标准连接字符串(非SRV),格式类似:
mongodb://myusername:mypassword@cluster0-shard-00-00.5ldtt3z.mongodb.net:27017,cluster0-shard-00-01.5ldtt3z.mongodb.net:27017,cluster0-shard-00-02.5ldtt3z.mongodb.net:27017/bot?ssl=true&replicaSet=atlas-q5c7wq-shard-0&authSource=admin&retryWrites=true&w=majority
将此字符串替换到环境变量中测试。
3. 升级MongoDB Node.js驱动版本
当前使用的4.13.0版本可能存在DNS解析相关的已知问题,尝试升级到4.x系列的最新稳定版(或兼容MongoDB 5.0的5.x版本):
在Replit的package.json中修改mongodb版本:
"dependencies": { "mongodb": "^4.17.2" }
然后在Shell中执行npm install更新依赖。
4. 检查Replit网络连通性
在Replit Shell中测试端口连通性:
telnet ac-8q8dm3y-shard-00-00.5ldtt3z.mongodb.net 27017
或使用curl测试:
curl -v telnet://ac-8q8dm3y-shard-00-00.5ldtt3z.mongodb.net:27017
如果无法连通,可能是Replit的网络限制导致,可尝试联系Replit支持确认是否有IP段屏蔽。
5. 刷新MongoDB Atlas白名单
虽然已添加0.0.0.0/0,但Atlas的白名单设置可能存在缓存,尝试删除现有白名单条目,重新添加0.0.0.0/0并保存,等待1-2分钟后再测试连接。
内容的提问来源于stack exchange,提问作者user874737
相关产品推荐
相关产品推荐

