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

Mongoose连接MongoDB报错求助:ECONNREFUSED 127.0.0.1:27017

Mongoose连接MongoDB出现ECONNREFUSED错误的解决办法

问题描述

使用Mongoose官网提供的代码连接MongoDB时,反复出现connect ECONNREFUSED 127.0.0.1:27017错误,已尝试更换不同版本的Mongoose但问题依旧。

完整错误信息

connection error: MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
    at NativeConnection.Connection.openUri (F:\Web development\mong\node_modules\mongoose\lib\connection.js:824:32)
    at F:\Web development\mong\node_modules\mongoose\lib\index.js:380:10
    at F:\Web development\mong\node_modules\mongoose\lib\helpers\promiseOrCallback.js:41:5
    at new Promise (<anonymous>)
    at promiseOrCallback (F:\Web development\mong\node_modules\mongoose\lib\helpers\promiseOrCallback.js:40:10)    
    at Mongoose._promiseOrCallback (F:\Web development\mong\node_modules\mongoose\lib\index.js:1225:10)
    at Mongoose.connect (F:\Web development\mong\node_modules\mongoose\lib\index.js:379:20)
    at Object.<anonymous> (F:\Web development\mong\index.js:2:10)
    at Module._compile (node:internal/modules/cjs/loader:1126:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) { 'localhost:27017' => [ServerDescription] },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    logicalSessionTimeoutMinutes: undefined
  },
  code: undefined
}
node:internal/process/promises:279
            triggerUncaughtException(err, true /* fromPromise */);
            ^

MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
    at NativeConnection.Connection.openUri (F:\Web development\mong\node_modules\mongoose\lib\connection.js:824:32)        
    at F:\Web development\mong\node_modules\mongoose\lib\index.js:380:10
    at F:\Web development\mong\node_modules\mongoose\lib\helpers\promiseOrCallback.js:41:5
    at new Promise (<anonymous>)
    at promiseOrCallback (F:\Web development\mong\node_modules\mongoose\lib\helpers\promiseOrCallback.js:40:10)
    at Mongoose._promiseOrCallback (F:\Web development\mong\node_modules\mongoose\lib\index.js:1225:10)
    at Mongoose.connect (F:\Web development\mong\node_modules\mongoose\lib\index.js:379:20)
    at Object.<anonymous> (F:\Web development\mong\index.js:2:10)
    at Module._compile (node:internal/modules/cjs/loader:1126:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) {
      'localhost:27017' => ServerDescription {
        _hostAddress: HostAddress { isIPv6: false, host: 'localhost', port: 27017 },
        address: 'localhost:27017',
        type: 'Unknown',
        hosts: [],
        passives: [],
        arbiters: [],
        tags: {},
        minWireVersion: 0,
        maxWireVersion: 0,
        roundTripTime: -1,
        lastUpdateTime: 338285881,
        lastWriteDate: 0,
        error: MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017
            at connectionFailureError (F:\Web development\mong\node_modules\mongodb\lib\cmap\connect.js:379:20)
            at Socket.<anonymous> (F:\Web development\mong\node_modules\mongodb\lib\cmap\connect.js:302:22)
            at Object.onceWrapper (node:events:628:26)
            at Socket.emit (node:events:513:28)
            at emitErrorNT (node:internal/streams/destroy:157:8)
            at emitErrorCloseNT (node:internal/streams/destroy:122:3)
            at processTicksAndRejections (node:internal/process/task_queues:83:21) {
          [Symbol(errorLabels)]: Set(0) {}
        }
      }
    },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    logicalSessionTimeoutMinutes: undefined
  },
  code: undefined
}

使用的代码

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test', {useNewUrlParser: true, useUnifiedTopology: true});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  // we're connected!
  console.log('hello there');
});

解决步骤

  • 检查MongoDB服务状态
    Windows用户:按下Win+R输入services.msc打开服务管理器,找到MongoDB服务,确认状态为“正在运行”,未运行则右键启动;
    macOS/Linux用户:终端执行sudo systemctl start mongod(systemd系统)或sudo service mongod start,也可直接运行mongod命令手动启动服务。

  • 验证端口监听情况
    检查MongoDB是否在27017端口监听:

    • Windows:执行netstat -ano | findstr :27017;
    • macOS/Linux:执行lsof -i :27017;
      若端口未被监听,查看MongoDB配置文件(通常为mongod.conf)中的net.port项,确认端口配置正确,若修改过端口,需同步调整连接字符串中的端口号。
  • 修正连接字符串
    尝试用127.0.0.1替代localhost,避免DNS解析问题,连接字符串改为:mongodb://127.0.0.1:27017/test;
    若MongoDB设置了用户名密码,需修改为:mongodb://用户名:密码@127.0.0.1:27017/test。

  • 检查防火墙设置
    临时关闭本地防火墙,测试是否能正常连接,若关闭后连接成功,需在防火墙中添加27017端口的允许规则。

优化后的代码示例

const mongoose = require('mongoose');

async function connectDatabase() {
  try {
    await mongoose.connect('mongodb://127.0.0.1:27017/test', {
      useNewUrlParser: true,
      useUnifiedTopology: true
    });
    console.log('数据库连接成功');
  } catch (error) {
    console.error('连接失败:', error);
    process.exit(1);
  }
}

connectDatabase();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 09:18:30