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

Node.js无法连接本地MongoDB v6.0问题求助

Node.js连接本地MongoDB失败但Python可正常连接的问题排查与解决

问题现象

  • 本地MongoDB v6.0服务正常运行(执行mongod命令可确认)
  • Python能正常连接并与数据库交互,但Node.js无法建立连接,报错MongoServerSelectionError: connect ECONNREFUSED ::1:27017
  • 已尝试关闭防火墙、检查服务状态,问题仍未解决

相关信息

Node.js代码

const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';

MongoClient.connect(url, function(err, client) {
  if (err) throw err;

  const db = client.db('inventory');
  db.createCollection('klci', function(err, res) {
    if (err) throw err;
    console.log('Collection klci created!');
    client.close();
  });
});

报错信息

C:\Users\Laith\Desktop\mongodb test\node_modules\mongodb\lib\sdam\topology.js:278
                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\Laith\Desktop\mongodb test\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: 1105815,
        lastWriteDate: 0,
        error: MongoNetworkError: connect ECONNREFUSED ::1:27017
            at connectionFailureError (C:\Users\Laith\Desktop\mongodb test\node_modules\mongodb\lib\cmap\connect.js:370:20)
            at Socket.<anonymous> (C:\Users\Laith\Desktop\mongodb test\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
      }
    },
    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.16.0

MongoDB配置文件网络设置

net:
ipv6: true
bindIp: localhost
port: 27017

连接时MongoDB日志

{"t":{"$date":"2023-05-13T08:40:02.765-06:00"},"s":"I", "c":"NETWORK", "id":22943, "ctx":"listener","msg":"Connection accepted","attr":{"remote":"[::1]:52502","uuid":"4dc4df45-e01f-4eed-b17f-8ce5f3abe849","connectionId":5,"connectionCount":4}}
{"t":{"$date":"2023-05-13T08:40:02.766-06:00"},"s":"I", "c":"NETWORK", "id":51800, "ctx":"conn5","msg":"client metadata","attr":{"remote":"[::1]:52502","client":"conn5","doc":{"driver":{"name":"nodejs","version":"5.5.0"},"platform":"Node.js v18.16.0, LE","os":{"name":"win32","architecture":"x64","version":"10.0.19045","type":"Windows_NT"}}}}


解决方案

从报错和日志分析,Node.js v18+默认优先用IPv6解析localhost(对应地址::1),但MongoDB仅绑定了localhost(Windows环境下localhost默认映射为IPv4的127.0.0.1),导致连接被拒绝。可通过以下两种方式解决:

方式1:修改Node.js连接URL

将连接URL改为强制使用IPv4地址,绕过IPv6解析:

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

方式2:修改MongoDB绑定地址

在MongoDB配置文件中,将bindIp改为同时支持IPv4和IPv6的地址,重启服务后生效:

net:
ipv6: true
bindIp: 127.0.0.1,::1
port: 27017

验证:修改后重新运行Node.js代码,应能正常创建集合并输出Collection klci created!。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 01:07:08