本地MongoDB连接超时及改IP后无输出进程不终止问题求助
MongoDB连接问题排查与解决
问题描述
从w3schools获取的MongoDB连接代码:
var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/mydb"; MongoClient.connect(url, function(err, db) { if (err) throw err; console.log("Database created!"); db.close(); });
初始运行错误
执行代码时出现如下错误:
const timeoutError = new error_1.MongoServerSelectionError(`Server selection timed out after ${serverSelectionTimeoutMS} ms`, this.description); ^ MongoServerSelectionError: connect ECONNREFUSED ::1:27017 at Timeout._onTimeout (D:\Node\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: 116599938, lastWriteDate: 0, error: MongoNetworkError: connect ECONNREFUSED ::1:27017 at connectionFailureError (D:\Node\node_modules\mongodb\lib\cmap\connect.js:379:20) at Socket.<anonymous> (D:\Node\node_modules\mongodb\lib\cmap\connect.js:285: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) { [Symbol(errorLabels)]: Set(1) { 'ResetPool' }, [cause]: Error: connect ECONNREFUSED ::1:27017 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494: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 (D:\Node\node_modules\mongodb\lib\cmap\connect.js:379:20) at Socket.<anonymous> (D:\Node\node_modules\mongodb\lib\cmap\connect.js:285: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) { [Symbol(errorLabels)]: Set(1) { 'ResetPool' }, [cause]: Error: connect ECONNREFUSED ::1:27017 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16) { errno: -4078, code: 'ECONNREFUSED', syscall: 'connect', address: '::1', port: 27017 } } } Node.js v18.14.2
修改后的异常现象
将localhost改为127.0.0.1后,错误消失,但终端未打印Database created!,且代码进程无法自动终止。
原因分析
初始连接错误原因:
新版Node.js和部分操作系统中,localhost会优先解析为IPv6地址::1,但默认安装的MongoDB通常只监听IPv4的127.0.0.1端口,未开启IPv6监听,导致连接被拒绝。修改后无日志、进程不终止原因:
w3schools的代码适配的是MongoDB旧版驱动(v2.x及以下),而当前安装的是新版驱动(v4+)。新版驱动中:MongoClient.connect的回调函数第二个参数是client(客户端实例),而非旧版的db(数据库实例);- 旧版的
db.close()方法在新版中不存在,导致连接池未被正确关闭,进程无法退出;同时因为回调逻辑错误,console.log也不会执行。
解决方法
方法一:修正代码适配新版MongoDB驱动
将代码修改为以下形式(兼容新版驱动):
const MongoClient = require('mongodb').MongoClient; const url = "mongodb://127.0.0.1:27017/mydb"; MongoClient.connect(url) .then(client => { console.log("Database created!"); // 若需要操作数据库,可通过client.db()获取实例 // const db = client.db('mydb'); client.close(); // 关闭客户端实例,释放连接池 process.exit(); // 主动终止进程(可选,若close后进程仍不退出可添加) }) .catch(err => { console.error(err); process.exit(1); });
或者使用async/await写法:
const MongoClient = require('mongodb').MongoClient; const url = "mongodb://127.0.0.1:27017/mydb"; async function connectDB() { let client; try { client = await MongoClient.connect(url); console.log("Database created!"); // const db = client.db('mydb'); } catch (err) { console.error(err); } finally { if (client) { await client.close(); } process.exit(); } } connectDB();
方法二:让MongoDB监听IPv6地址(可选)
如果想继续使用localhost连接,可修改MongoDB配置文件(mongod.conf),添加IPv6监听:
net: bindIp: 127.0.0.1,::1
修改后重启MongoDB服务,即可通过localhost正常连接。
内容的提问来源于stack exchange,提问作者human
相关产品推荐
相关产品推荐

