Mongoose/MongoDB 'MongoServerError: Authentication failed.' with the docker MONGO_INITDB_ROOT_USERNAME user: add ?authSource=admin to mongodb://.../mydb
Fix: when you log in as the root user created by the official mongo image (MONGO_INITDB_ROOT_USERNAME / MONGO_INITDB_ROOT_PASSWORD), add authSource=admin to the URI: mongodb://${MONGO_USER}:${MONGO_PASSWORD}@mongo:27017/app?authSource=admin. That user lives in the admin database. If the URI names another database (/app) and has no authSource, the driver authenticates against that database, finds no such user and fails with 'MongoServerError: Authentication failed.' Mongoose 8 shows the same error because it uses this driver. The opposite mistake fails too: an application user created with db.getSiblingDB('app').createUser(...) authenticates with /app and fails with ?authSource=admin. So authSource must name the database where the user was created, not the database you want to read. Reproduced on mongo:8.0.38 with mongosh: root + /app gives Authentication failed, root + /app?authSource=admin or /admin pings OK, and appuser created in app works only without authSource=admin. For a cleaner setup, create a least-privilege app user (readWrite on app) in a /docker-entrypoint-initdb.d script and let the backend use that instead of root. Init scripts only run on an empty data volume, so if you change credentials later, remove the volume.