MongoDB连接失败求助:Node.js代码无法插入数据
Node.js连接MongoDB失败:ECONNREFUSED ::1:27017
我的代码
var MongoClient = require("mongodb").MongoClient; var url = "mongodb://localhost:27017/"; MongoClient.connect(url,function(err,db){ if(err) throw err; var dbo = db.db("school"); dbo.createCollection("students",function(err,res){ console.log("collection created!!!"); }); var myObjList=[ { name:"rohit", age:15, gpa:4.9 }, { name:"rahul", age:17, gpa:4.7 } ] dbo.collection("students").insertMany(myObjList,function(err,res){ if(err) throw err; console.log(res); 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 (C:\Users\Administrator\node_modules\mongodb\lib\sdam\topology.js:278: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: 2471400, lastWriteDate: 0, error: MongoNetworkError: connect ECONNREFUSED ::1:27017 at connectionFailureError (C:\Users\Administrator\node_modules\mongodb\lib\cmap\connect.js:379:20) at Socket.<anonymous> (C:\Users\Administrator\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:1300: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\Administrator\node_modules\mongodb\lib\cmap\connect.js:379:20) at Socket.<anonymous> (C:\Users\Administrator\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:1300:16) { errno: -4078, code: 'ECONNREFUSED', syscall: 'connect', address: '::1', port: 27017 } } }
解决方法
启动MongoDB服务
先确认本地MongoDB服务是否运行:- Windows:打开命令提示符,执行
net start MongoDB;如果是手动启动,找到MongoDB安装目录的bin文件夹,运行mongod.exe - macOS/Linux:终端执行
sudo systemctl start mongod(systemd系统),或者直接运行mongod命令
服务启动后重新运行代码。
- Windows:打开命令提示符,执行
改用IPv4地址连接
错误显示连接的是IPv6地址::1,可能MongoDB未监听IPv6。修改连接URL为:var url = "mongodb://127.0.0.1:27017/";检查端口占用
确认27017端口未被其他程序占用:- Windows:
netstat -ano | findstr :27017 - macOS/Linux:
lsof -i :27017
若有占用,关闭对应进程或修改MongoDB监听端口。
- Windows:
修复代码异步逻辑
原代码中createCollection是异步操作,直接执行后续insertMany可能导致集合未创建完成就插入。调整代码逻辑,将插入操作放到集合创建的回调内:var MongoClient = require("mongodb").MongoClient; var url = "mongodb://127.0.0.1:27017/"; MongoClient.connect(url, function(err, db) { if(err) throw err; var dbo = db.db("school"); dbo.createCollection("students", function(err, res) { if(err) throw err; console.log("collection created!!!"); var myObjList = [ {name:"rohit", age:15, gpa:4.9}, {name:"rahul", age:17, gpa:4.7} ]; dbo.collection("students").insertMany(myObjList, function(err, res) { if(err) throw err; console.log("插入成功,共插入" + res.insertedCount + "条数据"); db.close(); }); }); });
内容的提问来源于stack exchange,提问作者rohit
相关产品推荐
相关产品推荐

