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

遇到MongoServerError: bad auth :Authentication Failed错误该如何解决?附MongoDB连接代码示例

Fixing MongoServerError: bad auth :Authentication Failed in Your MongoDB Connection

Let’s walk through the most common reasons you’re hitting this auth failure and how to fix them—this is a super common issue with MongoDB Atlas connections, so we’ll cover all the bases.

1. Double-Check Your Environment Variables

First, make sure your DB_USER and DB_PASS environment variables are actually loading correctly. Typos or missing setup are the #1 culprit here:

  • If you’re using dotenv, confirm your .env file lives in your project root, and variable names match exactly (they’re case-sensitive! db_user isn’t the same as DB_USER).
  • Add a temporary debug log to verify the values (don’t commit this to version control!):
    console.log("Loaded credentials:", process.env.DB_USER, process.env.DB_PASS);
    
    If either value is undefined or incorrect, fix your environment variable setup first.

2. Validate Your Atlas User Credentials

Even if your env vars are loading, the actual credentials might be wrong:

  • Head to your MongoDB Atlas dashboard, go to Database Access, and confirm the username matches exactly what you’re using (no extra spaces, misspellings).
  • If your password has special characters (like @, #, $), you need to URL-encode them in your connection string. Instead of manually encoding, use encodeURIComponent() for both username and password to avoid issues:
    const uri = `mongodb+srv://${encodeURIComponent(process.env.DB_USER)}:${encodeURIComponent(process.env.DB_PASS)}@cluster0.agq2x.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`;
    
  • Ensure your database user has permissions to access myFirstDatabase—at minimum, they should have the readWrite role assigned.

3. Fix Your Connection String Format

I noticed your connection string has & instead of &—that’s an HTML-escaped character, which will break the connection parameter parsing. Replace & with a plain & so your string looks like:

mongodb+srv://USER:PASS@cluster0.agq2x.mongodb.net/myFirstDatabase?retryWrites=true&w=majority

Also, double-check the cluster address (cluster0.agq2x.mongodb.net) is copied correctly from Atlas—even one wrong character will cause issues.

4. Check Atlas IP Whitelisting

Sometimes MongoDB Atlas returns an auth failure error when the real issue is that your IP isn’t whitelisted. Head to Network Access in your Atlas dashboard:

  • Add your current public IP address to the whitelist.
  • For testing, you can temporarily allow all IPs (0.0.0.0/0)—just remember to remove this later for security.

5. Ensure Driver and Server API Compatibility

You’re using ServerApiVersion.v1, so make sure your MongoDB Node.js driver is up to date. Outdated drivers can have compatibility issues with the stable server API:

npm install mongodb@latest

Corrected Example Code

Here’s a cleaned-up version of your code with these fixes applied:

require('dotenv').config(); // Include this if using dotenv
const { MongoClient, ServerApiVersion } = require('mongodb');

const uri = `mongodb+srv://${encodeURIComponent(process.env.DB_USER)}:${encodeURIComponent(process.env.DB_PASS)}@cluster0.agq2x.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`;

const client = new MongoClient(uri, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  serverApi: ServerApiVersion.v1
});

// Test the connection
async function testConnection() {
  try {
    await client.connect();
    console.log("Successfully connected to MongoDB!");
  } catch (error) {
    console.error("Connection failed:", error);
  } finally {
    await client.close();
  }
}

testConnection();

Start with the simplest checks (env vars, connection string syntax) first—most of the time, that’s where the issue is. If none of these work, check the Atlas logs for more specific error details to narrow it down.

内容的提问来源于stack exchange,提问作者Md. Rifat Mahmud Rakib

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 21:32:35