Node.js与MongoDB连接报错MongooseServerSelectionError求助
解决MongooseServerSelectionError: connect ECONNREFUSED ::1:27017问题
错误详情
POST /api/user/createAccount 200 3.747 ms - 607 C:\Users\hp\Desktop\personal\backend\node_modules\mongoose\lib\connection.js:805 err = new ServerSelectionError(); ^ MongooseServerSelectionError: connect ECONNREFUSED ::1:27017 at _handleConnectionErrors (C:\Users\hp\Desktop\personal\backend\node_modules\mongoose\lib\connection.js:805:11) at NativeConnection.openUri (C:\Users\hp\Desktop\personal\backend\node_modules\mongoose\lib\connection.js:780: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, lastUpdateTime: 4152731, lastWriteDate: 0, error: MongoNetworkError: connect ECONNREFUSED ::1:27017 at connectionFailureError (C:\Users\hp\Desktop\personal\backend\node_modules\mongodb\lib\cmap\connect.js:367:20) at Socket.<anonymous> (C:\Users\hp\Desktop\personal\backend\node_modules\mongodb\lib\cmap\connect.js:290:22) at Object.onceWrapper (node:events:629:26) at Socket.emit (node:events:514:28) at emitErrorNT (node:internal/streams/destroy:151:8) at emitErrorCloseNT (node:internal/streams/destroy:116:3) at process.processTicksAndRejections (node:internal/process/task_queues:82:21) { cause: Error: connect ECONNREFUSED ::1:27017 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1495: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 } Node.js v18.17.0 [nodemon] app crashed - waiting for file changes before starting...
排查与解决步骤
确认MongoDB服务状态
打开命令提示符,运行net start MongoDB(Windows)或brew services start mongodb-community(Mac),检查服务是否正在运行。如果服务未启动,手动启动后再测试接口。强制使用IPv4连接MongoDB
即使启用了IPv6,可能存在IPv6配置问题。修改Mongoose连接字符串,将localhost替换为127.0.0.1,明确指定IPv4地址:mongoose.connect('mongodb://127.0.0.1:27017/your-db-name', { useNewUrlParser: true, useUnifiedTopology: true });检查MongoDB配置文件
打开MongoDB的mongod.cfg文件,确认net.bindIp配置是否包含127.0.0.1和::1,如果只绑定了其中一个,会导致另一协议无法连接。修改后重启MongoDB服务:net: bindIp: 127.0.0.1,::1 port: 27017验证端口占用情况
运行netstat -ano | findstr :27017(Windows)或lsof -i :27017(Mac/Linux),查看27017端口是否被其他进程占用。如果有,终止占用进程或修改MongoDB端口。添加Mongoose连接重试机制
接口调用一段时间后报错,可能是连接超时或断开未重连。在Mongoose连接配置中添加重试参数:mongoose.connect('mongodb://127.0.0.1:27017/your-db-name', { useNewUrlParser: true, useUnifiedTopology: true, serverSelectionTimeoutMS: 5000, socketTimeoutMS: 45000, reconnectTries: Number.MAX_VALUE, reconnectInterval: 1000 });检查nodemon重启逻辑
确认nodemon是否在文件变更时重启服务,但未正确关闭旧的MongoDB连接。可以在server.js中添加进程退出时的连接关闭逻辑:process.on('SIGINT', async () => { await mongoose.connection.close(); process.exit(0); });
内容的提问来源于stack exchange,提问作者rishabh
相关产品推荐
相关产品推荐

