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

使用Node.js驱动程序认证MongoDB失败的求助

MongoDB Node.js驱动认证失败排查

问题概况

我创建了拥有readWrite数据库权限的MongoDB用户,该用户可通过mongosh命令行和MongoDB Compass正常登录认证,但使用Node.js官方驱动连接时,始终抛出认证失败错误:

MongoServerError: Authentication failed.
...
ok: 0,
code: 18,
codeName: "AuthenticationFailed",
connectionGeneration: 0

当前实现代码

代码参考官方文档编写,未使用Mongoose等第三方包装库:

const { MongoClient } = require("mongodb");
const myMongo = new MongoClient(`mongodb://${encodeURIComponent(username)}:${encodeURIComponent(password)}@localhost:27017`);
myMongo.connect();
  • 用encodeURIComponent处理用户名和密码,是为了避免密码含特殊字符时触发MongoParseError: Password contains unescaped characters错误
  • 尝试手动指定authMechanism参数,问题依旧
  • 未开启数据库认证前,Node.js可正常连接;用户名和密码本身有效,在mongosh和Compass中均能正常使用

项目依赖配置(package.json)

{
  "name": "vxsacademy",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "cd src; node index.js"
  },
  "keywords": [],
  "author": "",
  "license": "GPL-3.0",
  "dependencies": {
    "@types/node": "^18.0.6",
    "bson": "^6.1.0",
    "crypto-js": "^4.1.1",
    "mongodb": "^6.1.0"
  }
}

内容的提问来源于stack exchange,提问作者Vexcess

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 04:15:08