Node.js连接MongoDB遇MongoServerSelectionError问题求助
Node.js连接MongoDB出现MongoServerSelectionError(ETIMEDOUT)的排查方案
我用Node.js连接MongoDB时触发MongoServerSelectionError错误,报错信息为:MongoServerSelectionError: connect ETIMEDOUT 15.206.14.158:27017。已经按教程将IP地址加入白名单,但问题仍未解决。
我的代码:
const { MongoClient, ServerApiVersion } = require("mongodb"); async function main() { /** * Connection URI. Update <username>, <password>, and <your-cluster-url> to reflect your cluster. */ const uri = "mongodb+srv://bran:R8VP2F3ZvEZWRi5l@cluster0.hd6phlm.mongodb.net/?retryWrites=true&w=majority"; const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true, }); try { // Connect to the MongoDB cluster await client.connect(); // Make the appropriate DB calls await listDatabases(client); } catch (e) { console.error("the error: ", e); } finally { await client.close(); } } main().catch(console.error); async function listDatabases(client) { databasesList = await client.db().admin().listDatabases(); console.log("Databases:"); databasesList.databases.forEach((db) => console.log(` - ${db.name}`)); }
完整报错信息:
MongoServerSelectionError: connect ETIMEDOUT 15.206.14.158:27017 at Timeout._onTimeout (E:\node-mongo-connect\node_modules\mongodb\lib\sdam\topology.js:293:38) at listOnTimeout (node:internal/timers:559:17) at processTimers (node:internal/timers:502:7) { reason: TopologyDescription { type: 'ReplicaSetNoPrimary', servers: Map(3) { 'ac-mg9lmct-shard-00-00.hd6phlm.mongodb.net:27017' => [ServerDescription], 'ac-mg9lmct-shard-00-01.hd6phlm.mongodb.net:27017' => [ServerDescription], 'ac-mg9lmct-shard-00-02.hd6phlm.mongodb.net:27017' => [ServerDescription] }, stale: false, compatible: true, heartbeatFrequencyMS: 10000, localThresholdMS: 15, setName: 'atlas-hltwao-shard-0', maxElectionId: null, maxSetVersion: null, commonWireVersion: 0, logicalSessionTimeoutMinutes: null }, code: undefined, [Symbol(errorLabels)]: Set(0) {} }
排查与解决步骤:
核对白名单配置
- 确认添加的是当前设备的公网IP,而非内网IP(如192.168.x.x、10.x.x.x这类)
- 临时添加
0.0.0.0/0(允许所有IP访问)测试,排除白名单配置错误(测试后务必改回,避免安全风险)
检查网络连通性
- 用ping命令测试目标IP:
ping 15.206.14.158,看是否能正常连通 - 用telnet或nc测试端口开放情况:
telnet 15.206.14.158 27017或nc -zv 15.206.14.158 27017 - 确认本地防火墙、杀毒软件未拦截27017端口的出站请求
- 若处于公司/校园网络,联系管理员确认是否允许访问MongoDB Atlas的27017端口
- 用ping命令测试目标IP:
优化代码配置
- 代码中已引入
ServerApiVersion但未使用,建议添加到MongoClient配置中提升兼容性:const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 // 新增该行 }); - 仔细核对连接URI中的用户名、密码、集群地址,确保无拼写错误
- 代码中已引入
确认集群状态
- 登录MongoDB控制台,查看集群是否正常运行,无停机、维护等异常情况
内容的提问来源于stack exchange,提问作者Riyad Sm
相关产品推荐
相关产品推荐

