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

MongoDB-NodeJS连接数据库无输出,程序无限加载问题求助

Node.js连接MongoDB无输出且无限加载问题

执行node sbom-backend1.js时程序无任何输出,陷入无限加载状态,需排查代码或环境问题。

原代码

var MongoClient = require('mongodb').MongoClient
const url = "mongodb://localhost:27017/"
const dbName = 'my-test'
const table = 'artifact'

MongoClient.connect(url, (err, client) => {
  const db = client.db(dbName);
  db.collection(table).find().toArray((err, artifact) => {
        if (err) throw err
        artifact.forEach((value) => {
        console.log(value.scriptname)
    })
    client.close()
  })
})

已完成的排查操作

  • 确认MongoDB服务正常运行且可通过mongo shell访问
  • 核对Node.js版本与MongoDB驱动的兼容性
  • 尝试创建新数据库test并连接
  • 使用127.0.0.1替代localhost作为连接地址
  • 参考建议调整代码

问题分析与解决方案

代码核心问题

原代码未处理MongoClient.connect阶段的错误:如果连接MongoDB时出现异常(比如权限验证失败、连接超时、配置不匹配),代码会直接跳过错误处理逻辑,既不输出错误信息,也不会关闭客户端连接,导致Node.js进程挂起,陷入无限加载状态。

修正后的代码

添加连接错误处理,并保证出错时也能关闭客户端:

var MongoClient = require('mongodb').MongoClient
const url = "mongodb://localhost:27017/"
const dbName = 'my-test'
const table = 'artifact'

MongoClient.connect(url, (err, client) => {
  // 优先处理连接错误
  if (err) {
    console.error('MongoDB连接失败:', err);
    return;
  }
  
  const db = client.db(dbName);
  db.collection(table).find().toArray((err, artifact) => {
    if (err) {
      console.error('查询数据失败:', err);
      client.close();
      return;
    }
    
    artifact.forEach((value) => {
      console.log(value.scriptname);
    });
    client.close();
  });
})

后续排查方向

  1. 运行修正后的代码,查看是否输出错误信息,定位具体问题
  2. 检查MongoDB服务器日志,确认是否有连接失败的记录
  3. 给连接URL添加超时参数,避免无限等待:mongodb://localhost:27017/?connectTimeoutMS=5000
  4. 在mongo shell中验证my-test数据库和artifact集合存在且有数据:
    use my-test;
    db.artifact.find();
    
  5. 确认MongoDB是否启用了身份验证,若启用需在连接URL中添加用户名密码:mongodb://username:password@localhost:27017/

内容的提问来源于stack exchange,提问作者Marc-Lorenz Dähmer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 19:50:17