I am trying to upgrade my express code from using Mongoose version 5.13.7 to 8.15.1 and I am not able to authenticate to my Mongo database anymore.
The code that used to work:
mongoose.connect("mongodb://localhost:3005/", {
useNewUrlParser: true,
useUnifiedTopology: true,
user: "mongoAdmin",
pass: "<password>",
dbName: "MyTest",
sslKey : "<contents of my private-key.pem file>",
sslCert: "<contents of my certificate.pem file>",
});
Now every permutation of options I try result in authentication failures. In particular,
mongoose.connect(`mongodb://mongoAdmin:<password>@localhost:3005/MyTest`);
fails, which by my read of the manual, ought to work.
I can run a mongo shell with the command line:
mongosh mongodb://127.0.0.1:3005/MyTest -u mongoAdmin -p '<password>' --authenticationDatabase admin
to successfully connect to the database.
Could someone please lend me a clue? I'm out of ideas.
Adding some log information from the mongod.log file for this request. Oddly, there are two successive log messages generated from this request, one succeeding then one failing:
{"t":{"$date":"2025-05-30T17:47:32.309-07:00"},"s":"I", "c":"ACCESS", "id":5286306, "ctx":"conn416","msg":"Successfully authenticated","attr":{"client":"127.0.0.1:39708","isSpeculative":true,"isClusterMember":false,"mechanism":"SCRAM-SHA-256","user":"mongoAdmin","db":"admin","result":0,"metrics":{"conversation_duration":{"micros":10132,"summary":{"0":{"step":1,"step_total":2,"duration_micros":33},"1":{"step":2,"step_total":2,"duration_micros":14}}}},"extraInfo":{}}}
{"t":{"$date":"2025-05-30T17:47:32.317-07:00"},"s":"I", "c":"ACCESS", "id":5286307, "ctx":"conn417","msg":"Failed to authenticate","attr":{"client":"127.0.0.1:39720","isSpeculative":true,"isClusterMember":false,"mechanism":"SCRAM-SHA-256","user":"mongoAdmin","db":"admin","error":"AuthenticationFailed: SCRAM authentication failed, storedKey mismatch","result":18,"metrics":{"conversation_duration":{"micros":17981,"summary":{"0":{"step":1,"step_total":2,"duration_micros":29},"1":{"step":2,"step_total":2,"duration_micros":10}}}},"extraInfo":{}}}
You'll need to tell Mongoose to authenticate against the admin database explicitly using the authSource
option.
mongoose.connect("mongodb://localhost:3005/", {
user: "mongoAdmin",
pass: "<password>",
dbName: "MyTest",
authSource: "admin",
useNewUrlParser: true,
useUnifiedTopology: true,
sslKey: "<contents of your private-key.pem file>",
sslCert: "<contents of your certificate.pem file>",
});
The connection string should look like this:
mongoose.connect("mongodb://mongoAdmin:<password>@localhost:3005/MyTest?authSource=admin");