MongoDB Connection Errors — Authentication Failed and Connection String Issues
Warningdatabase
Overview
Fix MongoDB connection errors including authentication failures, connection string parsing issues, replica set connectivity, and TLS configuration problems.
Key Details
- MongoDB uses connection strings in URI format: mongodb://user:pass@host:port/database
- Authentication database may differ from the application database (authSource parameter)
- Replica sets require all members listed in the connection string or SRV DNS records
- MongoDB Atlas uses SRV connection strings: mongodb+srv://user:pass@cluster.xxxxx.mongodb.net/
- Special characters in passwords must be URL-encoded in the connection string
Common Causes
- Authentication database mismatch — user created in 'admin' but connecting to application database
- Special characters in password not URL-encoded (@ becomes %40, : becomes %3A)
- Replica set member unreachable from the application server
- MongoDB Atlas IP whitelist not including the application server's IP address
Steps
- 1URL-encode special characters in the password: use encodeURIComponent() in Node.js or equivalent
- 2Add authSource parameter: 'mongodb://user:pass@host:27017/mydb?authSource=admin'
- 3For MongoDB Atlas: whitelist your server IP in Atlas > Network Access > Add IP Address
- 4Test connection from command line: 'mongosh "mongodb://user:pass@host:27017/mydb?authSource=admin"'
- 5Check MongoDB logs: '/var/log/mongodb/mongod.log' for authentication and connection error details
Tags
mongodbconnectionauthenticationconnection-stringdatabase
Related Items
More in Database
linux-mysql-error-codesLinux MySQL Error Codes — 1045, 2002, 1205 & Common Database Errors
Errorlinux-postgresql-common-errorsPostgreSQL Common Errors — Connection Refused, Authentication, and Query Failures
Warninglinux-redis-connection-errorsRedis Connection Errors — Server Connection Refused and Memory Limit Issues
WarningFrequently Asked Questions
authSource specifies which database contains the user credentials. By default, users are created in the 'admin' database. Add ?authSource=admin to your connection string if your user is in admin but you are connecting to a different database.