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

如何解决Mongoose连接MongoDB时的MongooseServerSelectionError错误?

解决Mongoose连接MongoDB出现MongooseServerSelectionError: connect ECONNREFUSED ::1:27017的问题

我用Mongoose编写了MongoDB连接代码,运行服务器后触发MongooseServerSelectionError: connect ECONNREFUSED ::1:27017错误,以下是我的连接代码及完整错误日志:

连接代码

const mongoose = require("mongoose");

const connectDatabase = () => {
  mongoose
    .connect("mongodb://localhost:27017/Ecommerce", {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    })
    .then(() => {
      console.log(`MongoDB connected successfully`);
    })
    .catch((err) => {
      console.log(err);
    });
};

module.exports = connectDatabase;

错误日志

Server is working on http://localhost:4000
MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
    at _handleConnectionErrors (E:\MERN PROJECT\E-Commers WebSite\node_modules\mongoose\lib\connection.js:791:11)
    at NativeConnection.openUri (E:\MERN PROJECT\E-Commers WebSite\node_modules\mongoose\lib\connection.js:766:11)
    at runNextTicks (node:internal/process/task_queues:60:5)
    at listOnTimeout (node:internal/timers:538:9)
    at process.processTimers (node:internal/timers:512:7) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) { 'localhost:27017' => [ServerDescription] },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    setName: null,
    maxElectionId: null,
    maxSetVersion: null,
    commonWireVersion: 0,
    logicalSessionTimeoutMinutes: null
  },
  code: undefined
}

解决方法

  • 检查MongoDB服务状态
    这是最常见的触发原因——MongoDB服务未启动。

    • Windows:按下Win+R输入services.msc打开服务管理器,找到MongoDB服务,确认状态为“正在运行”,未运行则右键启动。
    • macOS/Linux:终端执行sudo systemctl start mongod(systemd系统)或sudo service mongod start启动服务。
  • 替换连接地址为127.0.0.1
    部分系统中localhost会解析到IPv6地址::1,但MongoDB默认可能未监听IPv6协议。修改连接字符串为:

    mongoose.connect("mongodb://127.0.0.1:27017/Ecommerce")
    
  • 检查27017端口占用情况
    若其他程序占用了MongoDB默认的27017端口,会导致连接失败。

    • Windows:终端执行netstat -ano | findstr :27017获取占用端口的进程PID,打开任务管理器结束对应进程。
    • macOS/Linux:终端执行lsof -i :27017定位进程,用kill -9 <PID>终止占用进程。
  • 移除过时的连接选项
    Mongoose 6.x及以上版本已默认启用useNewUrlParser和useUnifiedTopology,手动配置反而可能引发兼容性问题,简化后的代码如下:

    const mongoose = require("mongoose");
    
    const connectDatabase = () => {
      mongoose
        .connect("mongodb://127.0.0.1:27017/Ecommerce")
        .then(() => {
          console.log(`MongoDB connected successfully`);
        })
        .catch((err) => {
          console.log(err);
        });
    };
    
    module.exports = connectDatabase;
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 23:27:27