Node.js连接MongoDB失败:connect ECONNREFUSED ::1:27017问题
报错信息
const timeoutError = new error_1.MongoServerSelectionError(
Server selection timed out after ${serverSelectionTimeoutMS} ms, this.description);
MongoServerSelectionError: connect ECONNREFUSED ::1:27017
at Timeout._onTimeout (C:\Users**\Desktop\MONGODB\NEW SERVER\node_modules\mongodb\lib\sdam\topology.js:278:38)
at listOnTimeout (node:internal/timers:569:17)
at process.processTimers (node:internal/timers:512:7) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) {
'localhost:27017' => ServerDescription {
address: 'localhost:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 491601161,
lastWriteDate: 0,
error: MongoNetworkError: connect ECONNREFUSED ::1:27017
at connectionFailureError (C:\Users**\Desktop\MONGODB\NEW SERVER\node_modules\mongodb\lib\cmap\connect.js:370:20)
at Socket. (C:\Users\ANMOL\Desktop\MONGODB\NEW SERVER\node_modules\mongodb\lib\cmap\connect.js:293:22)
at Object.onceWrapper (node:events:628:26)
at Socket.emit (node:events:513: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 ECONNREFUSED ::1:27017
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16) {
errno: -4078,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '::1',
port: 27017
},
[Symbol(errorLabels)]: Set(1) { 'ResetPool' }
},
topologyVersion: null,
setName: null,
setVersion: null,
electionId: null,
logicalSessionTimeoutMinutes: null,
primary: null,
me: null,
'$clusterTime': null
}
},
排查与解决步骤
确认mongod服务是否正常启动
查看运行mongod的终端输出,找有没有waiting for connections on port 27017的日志。如果有报错(比如数据目录不存在、权限不足),先解决这些基础问题。比如数据目录不存在的话,手动创建:mkdir C:\data\db也可以用命令测试端口连通性:
# Windows PowerShell Test-NetConnection localhost -Port 27017如果返回
TcpTestSucceeded: False,说明mongod没在监听27017端口。强制mongod监听IPv6或修改Node连接字符串
这个报错是Node尝试用IPv6地址::1连接,但mongod默认可能只监听IPv4的127.0.0.1。两种解决方式:- 启动mongod时指定监听所有地址:
或者明确指定IPv4和IPv6:mongod --bind_ip_allmongod --bind_ip 127.0.0.1,::1 - 修改Node代码里的MongoDB连接字符串,强制用IPv4:
// 把原来的 localhost 改成 127.0.0.1 const uri = 'mongodb://127.0.0.1:27017/your-db-name';
- 启动mongod时指定监听所有地址:
检查防火墙拦截
Windows Defender防火墙或第三方安全软件可能拦截了27017端口的连接。可以暂时关闭防火墙测试,如果能正常连接,就给MongoDB和Node.js添加允许通过防火墙的规则。检查mongod配置文件(如果用配置文件启动)
如果是用配置文件启动mongod,打开配置文件(比如mongod.cfg),找到net部分的bindIp配置,确保包含127.0.0.1或::1,或者设置为0.0.0.0允许所有地址:net: port: 27017 bindIp: 127.0.0.1,::1 # 或者 0.0.0.0修改后重启mongod服务。
内容的提问来源于stack exchange,提问作者ANMOL

