You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

项目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系统可通过以下方式检查:

    1. 按下Win + R输入services.msc打开服务管理器
    2. 找到MongoDB服务,查看状态是否为“正在运行”
    3. 若未运行,右键选择“启动”;也可在命令行执行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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 12:11:03