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

Node.js MongoDB驱动连接失败求助:ECONNREFUSED错误排查

Node.js驱动无法连接MongoDB问题

问题现象

使用Node.js MongoDB驱动连接本地MongoDB时,抛出MongoServerSelectionError: connect ECONNREFUSED ::1:27017错误,已尝试将连接URL中的localhost改为127.0.0.1,问题仍未解决。

连接代码

const MongoClient = require("mongodb").MongoClient;
const assert = require("assert");

// connection URL
const url = "mongodb://localhost:27017/";

// database Name
const dbName = "fruitsDB";

// create a new MongoClient
const client = new MongoClient(url, {useNewUrlParser: true});

// use connect method to connect to the server
client.connect(function(err){
    assert.equal(null, err);
    console.log("connected to server successfully");

    const db = client.db(dbName);

    client.close();
});

完整错误信息

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\abhis\OneDrive\Desktop\fruitsProject\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: 'Single',
    servers: Map(1) {
      'localhost:27017' => ServerDescription {
        address: 'localhost:27017',
        type: 'Unknown',
        hosts: [],
        passives: [],
        arbiters: [],
        tags: {},
        minWireVersion: 0,
        maxWireVersion: 0,
        roundTripTime: -1,
        lastUpdateTime: 261314343,
        lastWriteDate: 0,
        error: MongoNetworkError: connect ECONNREFUSED ::1:27017
            at connectionFailureError (C:\Users\abhis\OneDrive\Desktop\fruitsProject\node_modules\mongodb\lib\cmap\connect.js:367:20)
            at Socket.<anonymous> (C:\Users\abhis\OneDrive\Desktop\fruitsProject\node_modules\mongodb\lib\cmap\connect.js:290:22)
            at Object.onceWrapper (node:events:629:26)
            at Socket.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 ECONNREFUSED ::1:27017
              at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1495: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.17.0

mongod服务器启动日志

{"t":{"$date":"2023-08-21T22:40:34.908+05:30"},"s":"I",  "c":"REPL",     "id":5853300, "ctx":"initandlisten","msg":"current featureCompatibilityVersion value","attr":{"featureCompatibilityVersion":"7.0","context":"startup"}}
{"t":{"$date":"2023-08-21T22:40:34.909+05:30"},"s":"I",  "c":"STORAGE",  "id":5071100, "ctx":"initandlisten","msg":"Clearing temp directory"}
{"t":{"$date":"2023-08-21T22:40:34.911+05:30"},"s":"I",  "c":"CONTROL",  "id":6608200, "ctx":"initandlisten","msg":"Initializing cluster server parameters from disk"}
{"t":{"$date":"2023-08-21T22:40:34.911+05:30"},"s":"I",  "c":"CONTROL",  "id":20536,   "ctx":"initandlisten","msg":"Flow Control is enabled on this deployment"}
{"t":{"$date":"2023-08-21T22:40:35.117+05:30"},"s":"I",  "c":"FTDC",     "id":20625,   "ctx":"initandlisten","msg":"Initializing full-time diagnostic data capture","attr":{"dataDirectory":"C:/data/db/diagnostic.data"}}
{"t":{"$date":"2023-08-21T22:40:35.121+05:30"},"s":"I",  "c":"REPL",     "id":6015317, "ctx":"initandlisten","msg":"Setting new configuration state","attr":{"newState":"ConfigReplicationDisabled","oldState":"ConfigPreStart"}}
{"t":{"$date":"2023-08-21T22:40:35.121+05:30"},"s":"I",  "c":"STORAGE",  "id":22262,   "ctx":"initandlisten","msg":"Timestamp monitor starting"}
{"t":{"$date":"2023-08-21T22:40:35.125+05:30"},"s":"I",  "c":"NETWORK",  "id":23015,   "ctx":"listener","msg":"Listening on","attr":{"address":"127.0.0.1"}}
{"t":{"$date":"2023-08-21T22:40:35.125+05:30"},"s":"I",  "c":"NETWORK",  "id":23016,   "ctx":"listener","msg":"Waiting for connections","attr":{"port":27017,"ssl":"off"}}

mongosh终端连接状态

$ mongosh
Current Mongosh Log ID: 64e3a30074e0279acc8ee81f
Connecting to:          mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.10.5
Using MongoDB:          7.0.0
Using Mongosh:          1.10.5

------
   The server generated these startup warnings when booting
   2023-08-20T14:35:50.897+05:30: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
------

test> 

解决步骤

从日志可见,MongoDB服务仅绑定了IPv4地址127.0.0.1,但Node.js v18+默认优先解析localhost为IPv6地址::1,导致连接被拒绝。以下是几种可行的解决方法:

方法1:强制驱动使用IPv4

修改连接配置,指定IPv4地址并添加family:4参数:

const url = "mongodb://127.0.0.1:27017/";
const client = new MongoClient(url, {
  useNewUrlParser: true,
  family: 4 // 强制使用IPv4协议
});

方法2:修改MongoDB绑定地址

编辑MongoDB配置文件(通常为mongod.cfg),将net.bindIp设置为同时支持IPv4和IPv6:

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

修改后重启MongoDB服务。

方法3:调整Node.js DNS解析优先级

启动Node.js进程时添加参数,强制优先解析IPv4:

node --dns-result-order=ipv4first app.js

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 16:25:56