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

连接MongoDB Atlas遇MongooseServerSelectionError,请求协助修复

问题描述

使用Mongoose连接MongoDB Atlas集群时触发MongooseServerSelectionError,无法建立连接。已配置集群“允许所有IP访问”,但仍报错,错误日志显示存在MongoNetworkError(EACCES)。

错误日志

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: 
at _handleConnectionErrors (D:\REBOOT\All projects\E-commerce\demo\node_modules\mongoose\lib\connection.js:805:11)
at NativeConnection.openUri (D:\REBOOT\All projects\E-commerce\demo\node_modules\mongoose\lib\connection.js:780:11)
at async Server. (D:\REBOOT\All projects\E-commerce\demo\src\server.js:6:3) {
reason: TopologyDescription {
type: 'ReplicaSetNoPrimary',
servers: Map(3) {
'ac-tncrtmi-shard-00-01.pin5pfl.mongodb.net:27017' => ServerDescription {
address: 'ac-tncrtmi-shard-00-01.pin5pfl.mongodb.net:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 74743438,
lastWriteDate: 0,
error: MongoNetworkError: connect EACCES 64:ff9b::3e5:eb13:27017
at connectionFailureError (D:\REBOOT\All projects\E-commerce\demo\node_modules\mongodb\lib\cmap\connect.js:367:20)
at TLSSocket. (D:\REBOOT\All projects\E-commerce\demo\node_modules\mongodb\lib\cmap\connect.js:290:22)
at Object.onceWrapper (node:events:629:26)
at TLSSocket.emit (node:events:514:28)
at emitErrorNT (node:internal/streams/destroy:151:8)
at emitErrorCloseNT (node:internal/streams/destroy:116:3)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
cause: Error: connect EACCES 64:ff9b::3e5:eb13:27017
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1495:16) {
errno: -4092,
code: 'EACCES',
syscall: 'connect',
address: '64:ff9b::3e5:eb13',
port: 27017
},
[Symbol(errorLabels)]: Set(1) { 'ResetPool' }
},
topologyVersion: null,
setName: null,
setVersion: null,
electionId: null,
logicalSessionTimeoutMinutes: null,
primary: null,
me: null,
'$clusterTime': null
},
'ac-tncrtmi-shard-00-02.pin5pfl.mongodb.net:27017' => ServerDescription {
address: 'ac-tncrtmi-shard-00-02.pin5pfl.mongodb.net:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 74743023,
lastWriteDate: 0,
error: MongoNetworkError: connect EACCES 64:ff9b::b849:212b:27017
at connectionFailureError (D:\REBOOT\All projects\E-commerce\demo\node_modules\mongodb\lib\cmap\connect.js:367:20)
at TLSSocket. (D:\REBOOT\All projects\E-commerce\demo\node_modules\mongodb\lib\cmap\connect.js:290:22)
at Object.onceWrapper (node:events:629:26)
at TLSSocket.emit (node:events:514:28)
at emitErrorNT (node:internal/streams/destroy:151:8)
at emitErrorCloseNT (node:internal/streams/destroy:116:3)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
cause: Error: connect EACCES 64:ff9b::b849:212b:27017
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1495:16) {
errno: -4092,
code: 'EACCES',
syscall: 'connect',
address: '64:ff9b::b849:212b',
port: 27017
},
[Symbol(errorLabels)]: Set(1) { 'ResetPool' }
},
topologyVersion: null,
setName: null,
setVersion: null,
electionId: null,
logicalSessionTimeoutMinutes: null,
primary: null,
me: null,
'$clusterTime': null
},
'ac-tncrtmi-shard-00-00.pin5pfl.mongodb.net:27017' => ServerDescription {
address: 'ac-tncrtmi-shard-00-00.pin5pfl.mongodb.net:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 74743026,
lastWriteDate: 0,
error: MongoNetworkError: connect EACCES 64:ff9b::22ca:d412:27017
at connectionFailureError (D:\REBOOT\All projects\E-commerce\demo\node_modules\mongodb\lib\cmap\connect.js:367:20)
at TLSSocket. (D:\REBOOT\All projects\E-commerce\demo\node_modules\mongodb\lib\cmap\connect.js:290:22)
at Object.onceWrapper (node:events:629:26)
at TLSSocket.emit (node:events:514:28)
at emitErrorNT (node:internal/streams/destroy:151:8)
at emitErrorCloseNT (node:internal/streams/destroy:116:3)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
cause: Error: connect EACCES 64:ff9b::22ca:d412:27017
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1495:16) {
errno: -4092,
code: 'EACCES',
syscall: 'connect',
address: '64:ff9b::22ca:d412',
port: 27017
},
[Symbol(errorLabels)]: Set(1) { 'ResetPool' }
},
topologyVersion: null,
setName: null,
setVersion: null,
electionId: null,
logicalSessionTimeoutMinutes: null,
primary: null,
me: null,
'$clusterTime': null
}
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: 'atlas-2nwske-shard-0',
maxElectionId: null,
maxSetVersion: null,
commonWireVersion: 0,
logicalSessionTimeoutMinutes: null
},
code: undefined
}

Node.js v18.17.1
[nodemon] app crashed - waiting for file changes before starting...

项目代码

index.js

const express = require("express");
const cors = require("cors");

const app = express();
app.use(express.json());
app.use(cors());

app.get("/", (req, res) => {
  return res
    .status(200)
    .send({ message: "Welcome to ecommerce API-node", status: true });
});


module.exports = app;

server.js

const app = require(".");
const { connectDb } = require("./config/db");

const PORT = 5454;
app.listen(PORT, async () => {
  await connectDb();
  console.log("eCommerce API listening on PORT: ", PORT);
});

db.js

const mongoose = require("mongoose");
const mongoDbUrl =
  "mongodb+srv://xxxxxxxxxx:*************@cluster0.------------.mongodb.net/?retryWrites=true&w=majority";

const connectDb = () => {
  return mongoose.connect(mongoDbUrl);
};

module.exports = { connectDb };

排查与修复方案

  • 检查本地防火墙/安全软件:EACCES错误表示本地权限被拒绝,大概率是防火墙或杀毒软件阻止了Node.js访问27017端口。临时关闭防火墙或安全软件测试连接,若可行,添加Node.js或27017端口的允许规则。
  • 验证连接字符串正确性:确认db.js中的连接字符串里,用户名、密码、集群地址完全匹配MongoDB Atlas控制台提供的信息,若密码包含特殊字符需做URL编码。
  • 强制使用IPv4连接:错误日志显示连接的是IPv6地址,部分网络环境对IPv6支持不佳。在连接时添加family: 4参数强制使用IPv4:
    const connectDb = () => {
      return mongoose.connect(mongoDbUrl, {
        family: 4
      });
    };
    
  • 检查网络代理设置:若使用代理服务器,需配置Node.js绕过代理访问MongoDB Atlas域名,或在连接选项中配置代理信息。
  • 重启MongoDB Atlas集群:登录Atlas控制台找到对应集群,执行重启操作,待集群恢复后再尝试连接。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 01:54:50