Windows下Node.js连接MongoDB遇MongoServerSelectionError求助
问题:Node.js连接MongoDB报错MongoServerSelectionError: connect ECONNREFUSED ::1:27017
环境:Windows系统,MongoDB 6.0.6,Node.js 18.16.0
现象:注册表单提交后终端能正常打印请求数据,但无法建立数据库连接,报错如上。
index.js代码
var express = require('express'); var router = express.Router(); var MongoClient = require('mongodb').MongoClient; /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Express' }); }); router.post('/submit',function(req,res){ console.log(req.body) MongoClient.connect("mongodb://localhost:27017",function(err,client){ if(err) console.log('ERROR') else client.db('mydata').collection('user').insertOne(req.body) }) res.send("Got it") }) module.exports = router;
终端错误信息
POST /submit 200 31.648 ms - 6 [Object: null prototype] { first_name: 'tetew', last_name: 'fff', email: 'gggg', pw: 'fdf', pw_confirm: 'gg' } POST /submit 200 4.917 ms - 6 E:\Web\New Database\node_modules\mongodb\lib\sdam\topology.js:278 const timeoutError = new error_1.MongoServerSelectionError(`Server selection timed out after ${serverSelectionTimeoutMS} ms`, this.description); ^ MongoServerSelectionError: connect ECONNREFUSED ::1:27017 at Timeout._onTimeout (E:\Web\New Database\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: 58231053, lastWriteDate: 0, error: MongoNetworkError: connect ECONNREFUSED ::1:27017 at connectionFailureError (E:\Web\New Database\node_modules\mongodb\lib\cmap\connect.js:370:20) at Socket.<anonymous> (E:\Web\New Database\node_modules\mongodb\lib\cmap\connect.js:293: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: connect ECONNREFUSED ::1:27017 [nodemon] app crashed - waiting for file changes before starting...
解决思路
- 检查MongoDB服务状态:按Win+R输入
services.msc打开服务管理器,找到MongoDB服务,确认它处于“正在运行”状态。若未启动,右键点击启动,可设置为“自动启动”避免重复操作。 - 强制使用IPv4连接:Node.js 18默认优先用IPv6,而MongoDB可能未监听IPv6地址。把连接字符串从
mongodb://localhost:27017改成mongodb://127.0.0.1:27017。 - 验证端口占用情况:打开命令提示符,执行
netstat -ano | findstr :27017,查看27017端口是否被其他进程占用。若被占用,停止对应进程或修改MongoDB配置文件中的监听端口。 - 检查MongoDB连接配置:打开MongoDB配置文件(通常在
C:\Program Files\MongoDB\Server\6.0\bin\mongod.cfg),确认net.bindIp设置为127.0.0.1或0.0.0.0,确保允许本地连接。 - 完善代码错误处理:原代码仅打印
ERROR无法定位问题,建议补充详细错误日志,并在操作完成后关闭数据库连接:MongoClient.connect("mongodb://127.0.0.1:27017",function(err,client){ if(err) { console.error('数据库连接失败:', err); return; } client.db('mydata').collection('user').insertOne(req.body) .then(result => { console.log('数据插入成功:', result); client.close(); }) .catch(err => { console.error('数据插入失败:', err); client.close(); }) })
内容的提问来源于stack exchange,提问作者FEBIN DEVASSIA
相关产品推荐
相关产品推荐

