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

Node.js v18连接MongoDB Compass v6出现服务器超时错误求助

Node.js v18连接MongoDB Compass v6出现ECONNREFUSED错误的解决方法

问题背景

已安装并配置MongoDB Compass v6,通过npm install mongodb安装Node.js驱动,运行测试脚本时持续出现服务器超时错误,错误提示为MongoServerSelectionError: connect ECONNREFUSED ::1:27017。

测试脚本

var MongoClient = require('mongodb').MongoClient, format = require('util').format;
MongoClient.connect('mongodb://localhost:27017/local',
function (err, db) {
    if (err) {
        throw err;
    } else {
        console.log("successfully connected to the database");
    }
    db.close();
});

错误信息

>node test.js
..\mongodbTest\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:\xampp\htdocs\comp4621\mongodbTest\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: 10437142,
        lastWriteDate: 0,
        error: MongoNetworkError: connect ECONNREFUSED ::1:27017
            at connectionFailureError (C:\xampp\htdocs\comp4621\mongodbTest\node_modules\mongodb\lib\cmap\connect.js:367:20)
            at Socket.<anonymous> (C:\xampp\htdocs\comp4621\mongodbTest\node_modules\mongodb\lib\cmap\connect.js:290: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.14.2

解决步骤

1. 确认MongoDB服务已启动

  • Windows:按下Win+R输入services.msc,找到MongoDB服务,确认状态为「正在运行」,未运行则右键启动。
  • macOS/Linux:执行sudo systemctl start mongod启动服务,再用sudo systemctl status mongod确认运行状态。

2. 强制使用IPv4地址连接

将连接URI从mongodb://localhost:27017/local改为mongodb://127.0.0.1:27017/local。Node.js v18默认优先将localhost解析为IPv6地址::1,而MongoDB默认可能仅监听IPv4的127.0.0.1,导致连接被拒绝。

3. 检查MongoDB监听配置

找到MongoDB配置文件(Windows路径一般为C:\Program Files\MongoDB\Server\6.0\bin\mongod.cfg;macOS/Linux为/etc/mongod.conf):

  • 查找net段的bindIp配置,确保包含127.0.0.1;若需要支持IPv6,可改为bindIp: 127.0.0.1,::1,或设置bindIpAll: true允许所有IP访问。
  • 修改配置后重启MongoDB服务生效。

4. 升级MongoDB驱动至兼容版本

执行npm install mongodb@latest安装最新版驱动,确保与Node.js v18、MongoDB 6.x版本完全兼容。

5. 适配新版驱动的脚本写法(可选)

旧版回调写法仍可运行,但推荐使用Promise/async/await的现代写法,更易维护:

const { MongoClient } = require('mongodb');

async function connectToDB() {
  const uri = 'mongodb://127.0.0.1:27017/local';
  let client;
  try {
    client = await MongoClient.connect(uri);
    console.log('successfully connected to the database');
  } catch (err) {
    console.error('连接失败:', err);
  } finally {
    if (client) await client.close();
  }
}

connectToDB();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 17:24:53