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

MongoDB连接字符串认证失败问题排查求助

MongoDB连接认证失败排查(Deno环境)

问题描述

我编写了一段用于测试MongoDB连接的Deno代码:

import { MongoClient } from "./deps.ts";
import { load } from "./deps.ts";

await load({ export: true });

const mongoUri = Deno.env.get("MONGODB_URI");
if (!mongoUri) {
  throw new Error("MONGODB_URI is not defined in the environment variables");
}

const client = new MongoClient();

try {
  console.log("Attempting to connect to MongoDB...");
  await client.connect(mongoUri);
  console.log("Successfully connected to MongoDB!");
  
  // Test the connection
  const db = client.database("vitalityVista");
  const collections = await db.listCollections().toArray();
  console.log("Available collections:", collections);

} catch (error) {
  console.error("MongoDB connection error:", error);
  throw error;
} finally {
  await client.close();
} 

运行时出现认证失败错误:

Error: MongoError: "Connection failed: MongoError: {\"ok\":0,\"errmsg\":\"bad auth : authentication failed\",\"code\":8000,\"codeName\":\"AtlasError\"}"                                                                          
    at MongoClient.connect (https://deno.land/x/mongo@v0.32.0/src/client.ts:46:13)  
    at eventLoopTick (ext:core/01_core.js:175:7)
    at async file:///C:/Users/enman/OneDrive - BYU-Idaho/vitality_vista/backend/test_mongo.ts:15:3
error: Uncaught (in promise) Error: MongoError: "Connection failed: MongoError: {\"ok\":0,\"errmsg\":\"bad auth : authentication failed\",\"code\":8000,\"codeName\":\"AtlasError\"}"
      throw new MongoDriverError(`Connection failed: ${e.message || e}`);
            ^
    at MongoClient.connect (https://deno.land/x/mongo@v0.32.0/src/client.ts:46:13)  
    at eventLoopTick (ext:core/01_core.js:175:7)
    at async file:///C:/Users/enman/OneDrive - BYU-Idaho/vitality_vista/backend/test_mongo.ts:15:3

我确认连接字符串正确,用mongosh能正常连接,用户名密码也没有特殊字符,请问问题出在哪?

可能的原因及排查步骤

  • 环境变量加载异常:虽然调用了load({ export: true }),但可能环境变量未正确读取。可以在获取mongoUri后添加打印语句,确认加载的链接和mongosh使用的完全一致(注意不要泄露敏感信息):

    console.log("Loaded MONGODB_URI:", mongoUri);
    

    检查是否存在拼写错误、多余空格或链接片段遗漏。

  • 驱动版本兼容性问题:你使用的deno.land/x/mongo@v0.32.0版本较旧,可能与MongoDB Atlas的认证机制不兼容。尝试升级到最新稳定版,更新deps.ts中的依赖链接后重新运行。

  • 数据库权限不匹配:连接字符串中的默认数据库可能与代码指定的vitalityVista不一致,或者当前用户没有该数据库的访问权限。登录Atlas控制台检查用户权限,确保其对vitalityVista拥有读写权限;也可以在连接字符串末尾直接指定数据库,例如:mongodb+srv://user:pass@cluster0.mongodb.net/vitalityVista?retryWrites=true&w=majority。

  • Deno运行权限不足:Deno默认限制网络和环境变量访问,启动脚本时需添加必要权限:

    deno run --allow-net --allow-env test_mongo.ts
    
  • 依赖缓存异常:Deno可能缓存了旧版本的驱动文件,导致认证逻辑出错。可以清除缓存后重新加载依赖:

    deno cache --reload test_mongo.ts
    

内容的提问来源于stack exchange,提问作者Enmanuel De Los Santos Cruz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 10:28:18