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

MongoDB 6.0.1快速启动代码执行出现连接超时错误求助

MongoDB连接超时(ECONNREFUSED ::1:27017)问题

我用mongosh运行以下代码时遇到超时错误:

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

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

// Database Name
const dbName = 'fruitsDB';
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 successfully to server");

  const db = client.db(dbName);

  insertDocuments(db, function() {
    client.close();
  });
});

我已经把连接地址从mongodb://localhost:27017改成了mongodb://127.0.0.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\Samse\all\Desktop\WebDevLearning\BackEnd\FruitsProj\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: 3163819,
        lastWriteDate: 0,
        error: MongoNetworkError: connect ECONNREFUSED ::1:27017
            at connectionFailureError (C:\Users\Samse\all\Desktop\WebDevLearning\BackEnd\FruitsProj\node_modules\mongodb\lib\cmap\connect.js:370:20)
            at Socket.<anonymous> (C:\Users\Samse\all\Desktop\WebDevLearning\BackEnd\FruitsProj\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) {}
}

解决办法

1. 确认MongoDB服务是否在运行

报错核心是ECONNREFUSED,说明27017端口没有服务监听:

  • Windows:打开任务管理器→服务,查看MongoDB状态;或者命令行执行net start MongoDB启动服务。
  • macOS/Linux:执行systemctl status mongod查状态,未运行则用systemctl start mongod启动。

2. 强制MongoDB绑定IPv4地址

MongoDB可能默认只绑定了IPv6的::1,修改配置文件:

  • 找到mongod.conf(Windows一般在C:\Program Files\MongoDB\Server\对应版本\bin,Linux/macOS在/etc/mongod.conf)
  • 找到net节点,添加或修改bindIp为127.0.0.1:
    net:
      port: 27017
      bindIp: 127.0.0.1
    
  • 重启MongoDB服务生效。

3. 连接时强制使用IPv4

在MongoClient配置里加family: 4,强制走IPv4连接:

const client = new MongoClient(url, {
  useNewUrlParser: true,
  family: 4 // 指定使用IPv4
});

4. 检查防火墙设置

确保本地防火墙没有拦截27017端口的连接,可暂时关闭防火墙测试是否恢复正常。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 17:43:24