Node.js连接MongoDB报MongoServerSelectionError的解决方法
Node.js连接MongoDB报MongoServerSelectionError的解决办法
问题详情
Python操作MongoDB一切正常,但用Node.js连接时反复报错,错误类型为MongoServerSelectionError,具体提示connect ECONNREFUSED ::1:27017。
原Node.js代码
import { MongoClient } from "mongodb"; import assert from 'assert'; const url='mongodb://localhost:27017'; const dbname='myProject'; const client =new MongoClient(url); client.connect((err)=>{ assert.equal(null,err); console.log("connected sucessfully"); const db=client.db(dbname); client.close(); });
完整报错信息
const timeoutError = new error_1.MongoServerSelectionError(`Server selection timed out after ${serverSelectionTimeoutMS} ms`, this.description); ^ MongoServerSelectionError: connect ECONNREFUSED ::1:27017 at Timeout._onTimeout (C:\Users\hasan\mong\node_modules\mongodb\lib\sdam\topology.js:278:38) at listOnTimeout (node:internal/timers:569:17) at process.processTimers (node:internal/timers:512: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: 1070637, lastWriteDate: 0, error: MongoNetworkError: connect ECONNREFUSED ::1:27017 at connectionFailureError (C:\Users\hasan\mong\node_modules\mongodb\lib\cmap\connect.js:379:20) at Socket.<anonymous> (C:\Users\hasan\mong\node_modules\mongodb\lib\cmap\connect.js:285:22) at Object.onceWrapper (node:events:632:26) at Socket.emit (node:events:517: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) { [Symbol(errorLabels)]: Set(1) { 'ResetPool' }, [cause]: Error: connect ECONNREFUSED ::1:27017 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1555:16) { errno: -4078, code: 'ECONNREFUSED', syscall: 'connect', address: '::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, [Symbol(errorLabels)]: Set(0) {}, [cause]: MongoNetworkError: connect ECONNREFUSED ::1:27017 at connectionFailureError (C:\Users\hasan\mong\node_modules\mongodb\lib\cmap\connect.js:379:20) at Socket.<anonymous> (C:\Users\hasan\mong\node_modules\mongodb\lib\cmap\connect.js:285:22) at Object.onceWrapper (node:events:632:26) at Socket.emit (node:events:517: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) { [Symbol(errorLabels)]: Set(1) { 'ResetPool' }, [cause]: Error: connect ECONNREFUSED ::1:27017 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1555:16) { errno: -4078, code: 'ECONNREFUSED', syscall: 'connect', address: '::1', port: 27017 } } }
解决方法
1. 强制使用IPv4连接
Node.js默认优先解析localhost为IPv6地址(::1),但你的MongoDB可能只监听了IPv4的127.0.0.1。直接把连接URL里的localhost改成127.0.0.1即可:
const url='mongodb://127.0.0.1:27017';
2. 检查MongoDB绑定IP配置
打开MongoDB的配置文件(Windows下通常是mongod.cfg,Linux下为/etc/mongod.conf),找到net.bindIp配置项,确保它的值包含127.0.0.1或者设为0.0.0.0(允许所有IP访问)。修改后重启MongoDB服务生效。
3. 确认MongoDB服务状态与端口权限
- 重启MongoDB服务,确保服务正常运行。
- 检查防火墙或安全软件是否拦截了27017端口,可临时关闭测试是否能连接。
修正后的完整代码
import { MongoClient } from "mongodb"; import assert from 'assert'; const url='mongodb://127.0.0.1:27017'; const dbname='myProject'; const client = new MongoClient(url); client.connect((err)=>{ assert.equal(null,err); console.log("连接成功"); const db=client.db(dbname); client.close(); });
内容的提问来源于stack exchange,提问作者Hasan Khan
相关产品推荐
相关产品推荐

