User was not found for authentication
This authentication error means the username provided during a connection attempt does not exist in the authentication database specified. It is a common issue when credentials are misconfigured or the wrong auth source is used.
- 1Connecting with a username that has not been created in the target database
- 2A typo in the username portion of the connection string
- 3Specifying the wrong authentication database via the `authSource` parameter
- 4Attempting to authenticate against a database where the user does not have privileges
A client attempts to connect using a username that does not exist in the `admin` database.
// Assuming a user 'correct_user' exists, but 'wrong_user' does not.
// Connection attempt from a driver (e.g., Node.js):
const client = new MongoClient("mongodb://wrong_user:password@localhost:27017/?authSource=admin");
await client.connect();expected output
MongoServerError: UserNotFound: Could not find user "wrong_user" for db "admin"
Fix 1
Verify Username and `authSource`
WHEN Receiving this error during connection.
// Correct connection string const connectionString = "mongodb://correct_user:password@localhost:27017/?authSource=admin"; const client = new MongoClient(connectionString);
Why this works
Double-check that the username is spelled correctly and that the `authSource` parameter points to the database where the user was created (commonly 'admin' for administrative users).
Fix 2
Create the User in the Correct Database
WHEN The user genuinely does not exist yet.
// Connect as an admin user first
use admin
db.createUser({
user: "new_app_user",
pwd: passwordPrompt(),
roles: [{ role: "readWrite", db: "applicationDB" }]
})Why this works
Ensure the user is created with `db.createUser()` in the intended authentication database before applications attempt to connect with their credentials.
✕ Grant the user overly broad permissions like `root` or `clusterAdmin` just to fix the connection
This violates the principle of least privilege and creates a major security risk. Users should only have the specific roles they need for their intended database.
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev