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

MongoServerSelectionError连接失败求助:ECONNREFUSED ::1:27017

解决MongoServerSelectionError: connect ECONNREFUSED ::1:27017连接问题

问题背景

尝试用MongoClient连接MongoDB时触发MongoServerSelectionError: connect ECONNREFUSED ::1:27017,已尝试重启Windows MongoDB服务、手动启动数据库,问题仍存在。

报错代码

const { MongoClient } = require('mongodb')
const url = 'mongodb://localhost:27017';
const database = 'e-comm'
const client = new MongoClient(url);

async function getData()
{
    let result = await client.connect();
    let db = result.db(database);
    let collection = db.collection('products');
    let response =  await collection.find({}).toArray();
    console.log(response);
}
getData();

完整错误信息

C:\Users\HP\new node\node_modules\mongodb\lib\sdam\topology.js:292
                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\HP\new node\node_modules\mongodb\lib\sdam\topology.js:29
2:38)
    at listOnTimeout (node:internal/timers:564:17)
    at process.processTimers (node:internal/timers:507: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: 32573830,
        lastWriteDate: 0,
        error: MongoNetworkError: connect ECONNREFUSED ::1:27017
            at connectionFailureError (C:\Users\HP\new node\node_modules\mongodb\lib\cmap\co
nect.js:387:20)
            at Socket.<anonymous> (C:\Users\HP\new node\node_modules\mongodb\lib\cmap\connec
t.js:310: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:1300: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
      }
    },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    setName: null,
    maxElectionId: null,
    maxSetVersion: null,
    commonWireVersion: 0,
    logicalSessionTimeoutMinutes: null
  },
  code: undefined,
  [Symbol(errorLabels)]: Set(0) {}
}

Node.js v18.12.1

解决步骤

1. 强制使用IPv4地址连接

Node.js 18+版本默认将localhost解析为IPv6地址(::1),但多数MongoDB默认仅监听IPv4的127.0.0.1。修改连接URL为:

const url = 'mongodb://127.0.0.1:27017';

修改后重新运行代码,验证是否能连接。

2. 确认MongoDB服务状态

  • 打开任务管理器的「详细信息」标签,检查是否存在mongod.exe进程
  • 执行命令netstat -ano | findstr :27017,查看27017端口状态:
    • 无结果:说明MongoDB未启动,手动启动时需指定data目录,比如mongod --dbpath D:\mongodb\data
    • 有结果但进程ID不是mongod:终止对应进程后重启MongoDB

3. 配置MongoDB监听IPv6

若需要保留localhost连接,修改MongoDB配置文件(mongod.cfg):
找到net节点,添加IPv6绑定:

net:
  port: 27017
  bindIp: 127.0.0.1,::1  # 同时监听IPv4和IPv6

修改后重启MongoDB服务:

net stop MongoDB
net start MongoDB

4. 检查防火墙拦截

确认Windows防火墙未拦截27017端口:

  • 打开「Windows Defender防火墙」→「高级设置」→「入站规则」
  • 检查是否有允许mongod.exe或27017端口的规则,无则新建规则允许连接

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 09:25:12