项目Donars数据库无法连接MongoDB,终端提示无连接,请求排查错误
MongoDB连接失败(终端显示“无连接”)排查方案
问题详情
用户代码:
// 我的代码 const mongoose = require("mongoose"); mongoose.set("strictQuery", false); mongoose.connect("mongodb://localhost:27017/donars",{ }).then(() => { console.log(`连接成功`); }).catch((e) => { console.log(`无连接`); });
运行日志:
PS C:\Users\harsh\Downloads\organback\organbackend> npm run dev
organbackend@1.0.0 dev
nodemon src/app.js -e js,hbs[nodemon] 2.0.20
[nodemon] 随时输入rs重启服务
[nodemon] 监视路径: .
[nodemon] 监视扩展名: js,hbs
[nodemon] 启动node src/app.js
服务器运行在端口3001
无连接
解决步骤
确认MongoDB服务是否运行
Windows系统可通过以下方式检查:- 按下
Win + R输入services.msc打开服务管理器 - 找到MongoDB服务,查看状态是否为“正在运行”
- 若未运行,右键选择“启动”;也可在命令行执行
net start MongoDB启动服务
- 按下
补充连接配置参数
新版本Mongoose虽简化了配置,但添加必要参数可避免兼容性问题,修改后的连接代码:const mongoose = require("mongoose"); mongoose.set("strictQuery", false); mongoose.connect("mongodb://localhost:27017/donars", { useNewUrlParser: true, useUnifiedTopology: true }).then(() => { console.log(`连接成功`); }).catch((e) => { // 打印详细错误信息,方便定位问题 console.log(`连接失败:`, e.message); });排查连接地址问题
- 尝试将
localhost替换为127.0.0.1,避免DNS解析异常:mongodb://127.0.0.1:27017/donars - 确认MongoDB端口是否为27017,若修改过配置文件,需同步修改连接地址中的端口号
- 尝试将
处理权限认证(如果有设置)
如果MongoDB开启了用户名密码认证,连接地址需包含认证信息:mongoose.connect("mongodb://用户名:密码@localhost:27017/donars?authSource=admin", { useNewUrlParser: true, useUnifiedTopology: true })
内容的提问来源于stack exchange,提问作者Harsh Goyal
相关产品推荐
相关产品推荐

