How to Fix Authentication Failed Error in MongoDB
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.
mongo --username wrongUser --password wrongPass --authenticationDatabase admin
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.
mongodb://correctUser:correctPass@localhost:27017/mydatabase?authSource=adminPrevention
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().