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

Node.js连接MongoDB Compass遇ECONNREFUSED错误求助

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

我从零开始学习Node.js,尝试用Mongoose连接MongoDB Compass时,遇到了MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017错误。已经用mongosh确认连接字符串有效,MongoDB服务也处于运行状态,试过localhost、127.0.0.1、0.0.0.0等多种连接字符串都无法解决。

错误信息

MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
    at _handleConnectionErrors (/mnt/c/Users/user/Desktop/Programming/website/learningNode/mongoose/node_modules/mongoose/lib/connection.js:897:11)
    at NativeConnection.openUri (/mnt/c/Users/user/Desktop/Programming/website/learningNode/mongoose/node_modules/mongoose/lib/connection.js:848:11) {
  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,
        minRoundTripTime: 0,
        lastUpdateTime: 31356356,
        lastWriteDate: 0,
        error: MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017
            at connectionFailureError (/mnt/c/Users/user/Desktop/Programming/website/learningNode/mongoose/node_modules/mongodb/lib/cmap/connect.js:353:20)
            at Socket.<anonymous> (/mnt/c/Users/user/Desktop/Programming/website/learningNode/mongoose/node_modules/mongodb/lib/cmap/connect.js:268:44)
            at Object.onceWrapper (node:events:635:26)
            at Socket.emit (node:events:520:28)
            at emitErrorNT (node:internal/streams/destroy:170:8)
            at emitErrorCloseNT (node:internal/streams/destroy:129:3)
            at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
          [Symbol(errorLabels)]: Set(1) { 'ResetPool' },
          [cause]: Error: connect ECONNREFUSED 127.0.0.1:27017
              at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1607:16) {
            errno: -111,
            code: 'ECONNREFUSED',
            syscall: 'connect',
            address: '127.0.0.1',
            port: 27017
          }
        },
        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
}

相关代码

index.js

import express from "express";
import mongoose from "mongoose";
import dotenv from "dotenv";

// 创建Express实例
const app = express();

// 加载.env环境变量
dotenv.config();

// 设置端口,优先用环境变量,默认7000
const PORT = process.env.PORT || 7000;

// 获取MongoDB连接地址
const MONGOURL = process.env.MONGO_URL;

// 连接MongoDB并启动服务
mongoose.connect(MONGOURL).then(() => {
  console.log("数据库连接成功。");
  app.listen(PORT, () => {
    console.log(`服务运行在端口${PORT}`);
  });
});

.env配置

PORT = 8000
MONGO_URL = "mongodb://localhost:27017/dbconnect"

解决步骤

  1. 处理WSL网络映射问题
    从路径/mnt/c/...判断你是在WSL环境运行Node.js,WSL的localhost和Windows主机的localhost不共享网络空间,Windows上运行的MongoDB服务无法被WSL的localhost直接访问。

    • 解决:在Windows命令行执行ipconfig,找到以太网适配器WSL的IPv4地址(如172.17.0.1),将连接字符串中的localhost替换为该IP,修改后的.env配置为:
      MONGO_URL = mongodb://172.17.0.1:27017/dbconnect
      
  2. 移除.env中的引号
    .env文件里的MONGO_URL带了双引号,dotenv加载时会把引号也包含到连接字符串中,导致地址无效。直接去掉引号即可。

  3. 添加Mongoose连接选项(可选)
    虽然Mongoose 6+已默认启用必要的连接选项,但手动添加可避免版本兼容问题:

    mongoose.connect(MONGOURL, {
      useNewUrlParser: true,
      useUnifiedTopology: true
    }).then(() => {
      // 后续代码不变
    });
    
  4. 验证端口监听与防火墙
    在Windows主机执行netstat -ano | findstr :27017,确认MongoDB正在监听27017端口;同时检查Windows防火墙是否允许MongoDB的入站连接。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 06:00:09