Node.js连接MongoDB报错connect ECONNREFUSED 127.0.0.1:27017求助
Node.js连接MongoDB失败,但Compass和mongosh正常的解决方案
问题描述
我是MongoDB新手,尝试使用连接字符串mongodb://localhost:27017通过Node.js连接MongoDB时失败,但MongoDB Compass和mongosh命令行工具能正常连接。运行node app.js时出现的错误信息如下:
node app.js node:internal/process/promises:288 triggerUncaughtException(err, true /* fromPromise */); ^ AssertionError [ERR_ASSERTION]: null == MongoServerSelectionError: connect ECONNREFUSED ::1:27017 at Timeout._onTimeout (C:\Users\kokophone\Documents\MEGAsync\Mystudy\Web\Udemy\Angela Bootcamp\Mgphone One\MangoDB\FruitProject\node_modules\mongodb\lib\sdam\topology.js:292:38) at listOnTimeout (node:internal/timers:564:17) at process.processTimers (node:internal/timers:507:7) { [Symbol(errorLabels)]: Set(0) {}, code: undefined, reason: TopologyDescription { commonWireVersion: 0, compatible: true, heartbeatFrequencyM... at C:\Users\kokophone\Documents\MEGAsync\Mystudy\Web\Udemy\Angela Bootcamp\Mgphone One\MangoDB\FruitProject\app.js:15:10 at C:\Users\kokophone\Documents\MEGAsync\Mystudy\Web\Udemy\Angela Bootcamp\Mgphone One\MangoDB\FruitProject\node_modules\mongodb\lib\utils.js:349:66 { generatedMessage: true, code: 'ERR_ASSERTION', actual: null, expected: MongoServerSelectionError: connect ECONNREFUSED ::1:27017 at Timeout._onTimeout (C:\Users\kokophone\Documents\MEGAsync\Mystudy\Web\Udemy\Angela Bootcamp\Mgphone One\MangoDB\FruitProject\node_modules\mongodb\lib\sdam\topology.js:292:38) at listOnTimeout (node:internal/timers:564:17) at 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: 2313988, lastWriteDate: 0, error: MongoNetworkError: connect ECONNREFUSED ::1:27017 at connectionFailureError (C:\Users\kokophone\Documents\MEGAsync\Mystudy\Web\Udemy\Angela Bootcamp\Mgphone One\MangoDB\FruitProject\node_modules\mongodb\lib\cmap\connect.js:387:20) at Socket.<anonymous> (C:\Users\kokophone\Documents\MEGAsync\Mystudy\Web\Udemy\Angela Bootcamp\Mgphone One\MangoDB\FruitProject\node_modules\mongodb\lib\cmap\connect.js:310:22) at Object.onceWrapper (node:events:628:26) at Socket.emit (node:events:513: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], [Symbol(errorLabels)]: [Set] }, 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) {} }, operator: '==' } Node.js v18.12.1
解决方案
1. 替换localhost为127.0.0.1
将连接字符串改为mongodb://127.0.0.1:27017。问题根源是Node.js的DNS解析优先把localhost映射到IPv6地址::1,但你的MongoDB服务可能只监听了IPv4的127.0.0.1端口,导致连接被拒绝。而Compass和mongosh默认优先使用IPv4,所以能正常连接。
2. 配置MongoDB同时监听IPv4和IPv6
找到MongoDB的配置文件(通常名为mongod.conf),修改net模块的配置:
net: bindIp: 127.0.0.1,::1 port: 27017
修改后重启MongoDB服务,服务会同时监听IPv4和IPv6地址,此时用localhost也能正常连接。
3. 修复代码中的错误处理逻辑
错误信息里的AssertionError表明代码中可能使用了断言来处理连接错误,这不是标准的错误处理方式。改用try/catch捕获Promise异常:
const { MongoClient } = require('mongodb'); async function connectToMongoDB() { const uri = 'mongodb://127.0.0.1:27017'; const client = new MongoClient(uri); try { await client.connect(); console.log('成功连接到MongoDB'); // 后续数据库操作 } catch (error) { console.error('连接失败:', error); } finally { await client.close(); } } connectToMongoDB();
4. 检查驱动与服务器版本兼容性
运行npm list mongodb查看当前使用的MongoDB驱动版本,确保其与你的MongoDB服务器版本兼容。如果版本不匹配,可通过npm install mongodb@<兼容版本>调整驱动版本。
内容的提问来源于stack exchange,提问作者mgphone
相关产品推荐
相关产品推荐

