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

首次使用Node.js连接MongoDb遭遇MongooseServerSelectionError错误

解决MongooseServerSelectionError: connect ECONNREFUSED ::1:27017错误

错误代码如下:

MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
    at Connection.openUri (C:\Users\Dell\OneDrive\Desktop\New folder\node_modules\mongoose\lib\connection.js:825:32)
    at C:\Users\Dell\OneDrive\Desktop\New folder\node_modules\mongoose\lib\index.js:419:10
    at C:\Users\Dell\OneDrive\Desktop\New folder\node_modules\mongoose\lib\helpers\promiseOrCallback.js:41:5
    at new Promise (<anonymous>)
    at promiseOrCallback (C:\Users\Dell\OneDrive\Desktop\New folder\node_modules\mongoose\lib\helpers\promiseOrCallback.js:40:10)
    at Mongoose._promiseOrCallback (C:\Users\Dell\OneDrive\Desktop\New folder\node_modules\mongoose\lib\index.js:1272:10)
    at Mongoose.connect (C:\Users\Dell\OneDrive\Desktop\New folder\node_modules\mongoose\lib\index.js:418:20)
    at connect_db (C:\Users\Dell\OneDrive\Desktop\New folder\db.js:5:36)
    at Object.<anonymous> (C:\Users\Dell\OneDrive\Desktop\New folder\app.js:7:1)
    at Module._compile (node:internal/modules/cjs/loader:1159:14) {
  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
}

解决办法

1. 确认MongoDB服务是否启动

  • Windows:按Win+R输入services.msc,找到MongoDB服务右键启动;或命令行执行net start MongoDB
  • macOS:终端运行brew services start mongodb-community(brew安装版本)
  • Linux:终端执行sudo systemctl start mongod

2. 改用IPv4地址连接

错误里的::1是IPv6格式的localhost,部分MongoDB默认只监听IPv4的127.0.0.1。修改连接字符串:

mongoose.connect('mongodb://127.0.0.1:27017/你的数据库名');

3. 检查端口是否被占用

  • Windows:命令行输入netstat -ano | findstr :27017,找到PID后在任务管理器结束对应进程
  • macOS/Linux:终端执行lsof -i :27017,然后用kill -9 <进程PID>杀掉占用程序,再重启MongoDB

4. 检查MongoDB配置

打开MongoDB配置文件(如mongod.conf),确保net.bindIp设置为127.0.0.1或0.0.0.0(允许所有IP访问),修改后重启服务。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 07:55:32