0
0
MongodbDebug / FixBeginner · 3 min read

How to Fix Authentication Failed Error in MongoDB

To fix authentication failed errors in MongoDB, verify that your username and password are correct and match the database user credentials. Also, ensure your connection string specifies the correct authSource database where the user is defined.
🔍

Why This Happens

This error happens when MongoDB cannot verify your username and password. It usually means the credentials are wrong, the user does not exist in the specified database, or the connection string is missing the correct authentication database.

bash
mongo --username wrongUser --password wrongPass --authenticationDatabase admin
Output
Error: Authentication failed.
🔧

The Fix

Check your username and password carefully. Make sure the user exists in the authSource database you specify in your connection string. For example, if your user is created in the admin database, include ?authSource=admin in the URI.

text
mongodb://correctUser:correctPass@localhost:27017/mydatabase?authSource=admin
Output
Successfully connected to MongoDB.
🛡️

Prevention

Always create users with clear roles and note which database they belong to. Use environment variables to store credentials securely and avoid hardcoding them. Test your connection strings after creating users to catch errors early.

⚠️

Related Errors

Other common errors include user not found when the username is incorrect, or unauthorized when the user lacks proper roles. Fix these by verifying user existence and assigning correct roles with db.grantRolesToUser().

Key Takeaways

Verify username and password match the MongoDB user credentials exactly.
Include the correct authSource database in your connection string.
Create users with proper roles and test connections immediately.
Store credentials securely and avoid hardcoding them.
Check related errors like user not found or unauthorized for quick fixes.