Node.js中Mongoose数据库连接超时错误求助
报错信息
E:\Language\Web\Node Js\node_modules\mongodb\lib\sdam\topology.js:291 const timeoutError = new error_1.MongoServerSelectionError(`Server selection timed out after ${serverSelectionTimeoutMS} ms`, this.description); ^ MongoServerSelectionError: 连接被拒绝 ECONNREFUSED ::1:27017 在 Timeout._onTimeout (E:\Language\Web\Node Js\node_modules\mongodb\lib\sdam\topology.js:291:38) 在 listOnTimeout (node:internal/timers:564:17) 在 process.processTimers (node:internal/timers:507: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: 162220460, lastWriteDate: 0, error: MongoNetworkError: 连接被拒绝 ECONNREFUSED ::1:27017 在 connectionFailureError (E:\Language\Web\Node Js\node_modules\mongodb\lib\cmap\connect.js:387:20) 在 Socket. (E:\Language\Web\Node Js\node_modules\mongodb\lib\cmap\connect.js:310:22) 在 Object.onceWrapper (node:events:628:26) 在 Socket.emit (node:events:513:28) 在 emitErrorNT (node:internal/streams/destroy:151:8) 在 emitErrorCloseNT (node:internal/streams/destroy:116:3) 在 process.processTicksAndRejections (node:internal/process/task_queues:82:21) { cause: Error: 连接被拒绝 ECONNREFUSED ::1:27017 在 TCPConnectWrap.afterConnect [as oncomplete] (node:net:1300: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) {} }
排查解决步骤
确认MongoDB服务已启动
Windows系统:打开服务管理器(services.msc),找到MongoDB服务,确认状态为“正在运行”,未运行则右键启动;或在命令行执行net start MongoDB。
macOS/Linux:通过brew services start mongodb-community(Homebrew安装版),或sudo systemctl start mongod(系统包安装版)启动服务。改用IPv4格式连接地址
将Mongoose连接字符串中的localhost替换为127.0.0.1,示例代码:mongoose.connect('mongodb://127.0.0.1:27017/your_database_name');部分环境下
localhost会解析到IPv6地址::1,可能触发连接失败,切换为IPv4地址可规避该问题。检查防火墙/安全软件拦截
本地防火墙、杀毒软件可能阻止Node.js访问27017端口,可暂时关闭这类软件测试,或在防火墙规则中添加允许MongoDB服务、Node.js进程通过27017端口的权限。验证MongoDB配置
打开MongoDB配置文件(mongod.conf),检查bindIp项,确保设置为127.0.0.1或0.0.0.0(允许所有IP访问),避免仅绑定外部IP导致本地无法连接。修改后重启MongoDB服务。核对版本兼容性
确认Mongoose与MongoDB服务器版本兼容:比如Mongoose 7.x要求MongoDB 5.0+,Mongoose 6.x支持MongoDB 4.0+,版本不匹配也可能引发连接问题,可参考官方文档调整版本。
内容的提问来源于stack exchange,提问作者Nitish Singh

