Mongoose无法连接MongoDB Atlas集群问题求助
问题排查:MongoDB Atlas跨区域连接MongooseServerSelectionError
问题描述
刚创建部署在巴黎区域的MongoDB Atlas账户,已配置IP访问白名单(甚至添加了允许任意IP的0.0.0.0/0规则),但从孟买服务器连接时仍出现MongooseServerSelectionError,错误提示无法连接集群且副本集无主节点。
错误信息
MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://www.mongodb.com/docs/atlas/security-whitelist/ at NativeConnection.Connection.openUri (/home/sbfasto/backendfortsmith.sbfasto.com/node_modules/mongoose/lib/connection.js:825:32) at /home/sbfasto/backendfortsmith.sbfasto.com/node_modules/mongoose/lib/index.js:411:10 at /home/sbfasto/backendfortsmith.sbfasto.com/node_modules/mongoose/lib/helpers/promiseOrCallback.js:41:5 at new Promise (<anonymous>) at promiseOrCallback (/home/sbfasto/backendfortsmith.sbfasto.com/node_modules/mongoose/lib/helpers/promiseOrCallback.js:40:10) at Mongoose._promiseOrCallback (/home/sbfasto/backendfortsmith.sbfasto.com/node_modules/mongoose/lib/index.js:1285:10) at Mongoose.connect (/home/sbfasto/backendfortsmith.sbfasto.com/node_modules/mongoose/lib/index.js:410:20) at Object.<anonymous> (/home/sbfasto/backendfortsmith.sbfasto.com/app.js:15:10) at Module._compile (node:internal/modules/cjs/loader:1165:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1219:10) { reason: TopologyDescription { type: 'ReplicaSetNoPrimary', servers: Map(3) { 'ac-nbyh9mn-shard-00-00.6yz0ajv.mongodb.net:27017' => [ServerDescription], 'ac-nbyh9mn-shard-00-01.6yz0ajv.mongodb.net:27017' => [ServerDescription], 'ac-nbyh9mn-shard-00-02.6yz0ajv.mongodb.net:27017' => [ServerDescription] }, stale: false, compatible: true, heartbeatFrequencyMS: 10000, localThresholdMS: 15, setName: 'atlas-a81bt4-shard-0', maxElectionId: null, maxSetVersion: null, commonWireVersion: 0, logicalSessionTimeoutMinutes: null }, code: undefined }
连接代码
mongoose.connect("mongodb+srv://popcorn:<password>@fortsmith.6yz0ajv.mongodb.net/?retryWrites=true&w=majority", { useNewUrlParser: true, useUnifiedTopology: true }).then(() => console.log('mongo connected')).catch(err => console.log(err));
问题原因及解决办法
跨区域网络链路限制:孟买服务器到巴黎Atlas集群的网络可能存在阻断。在孟买服务器上执行端口连通性测试:
nc -zv ac-nbyh9mn-shard-00-00.6yz0ajv.mongodb.net 27017如果无法连通,联系服务器提供商检查出站防火墙规则,确认27017端口未被屏蔽,或更换网络环境尝试。
连接字符串密码编码问题:如果密码包含
@、:、/等特殊字符,必须进行URL编码。比如密码是abc@123,要替换成abc%40123再填入连接字符串。Mongoose配置与版本兼容问题:
useNewUrlParser和useUnifiedTopology在Mongoose 6.x及以上版本已默认启用,无需手动配置。若Mongoose版本较老,建议升级到最新稳定版;若版本较新,可删除这两个配置项后重试。Atlas集群初始化未完成:刚创建的集群可能需要几分钟完成副本集初始化,即便控制台显示"就绪",主节点选举仍可能在进行。等待10-15分钟后再尝试连接。
内容的提问来源于stack exchange,提问作者Ankit Patel
相关产品推荐
相关产品推荐

