Mongoose connection authentication failed
Solution 1:
I had the same problem many hours ago, and after all I solve it. My code is:
mongoose.createConnection(
"mongodb://localhost:27017/dbName",
{
"auth": {
"authSource": "admin"
},
"user": "admin",
"pass": "password"
}
);
Solution 2:
Further to @kartGIS, I've added one more option to make the connection code perfect as possible.
mongoose.connect("mongodb://localhost:27017/databaseName", {
"auth": { "authSource": "admin" },
"user": "username",
"pass": "password",
"useMongoClient": true
});
Solution 3:
Working fine for me on Mongodb 4.2 and Mongoose 5.7.13
Node.js
const Connect = async () => {
let url = "mongodb://localhost:27017/test_db";
try {
let client = await Mongoose.connect( url, {
poolSize: 10,
authSource: "admin",
user: "root",
pass: "root123",
useCreateIndex: true,
useNewUrlParser: true,
useUnifiedTopology: true
} );
log( "Database is connected!" );
} catch ( error ) {
log( error.stack );
process.exit( 1 );
}
}
Connect();
/etc/mongod.conf
systemLog:
destination: file
logAppend: true
path: /var/log/mongodb/mongod.log
storage:
dbPath: /var/lib/mongo
journal:
enabled: true
processManagement:
fork: true # fork and run in background
pidFilePath: /var/run/mongodb/mongod.pid # location of pidfile
timeZoneInfo: /usr/share/zoneinfo
net:
port: 27017
bindIp: 0.0.0.0
setParameter:
enableLocalhostAuthBypass: false
security:
authorization: enabled
Database User
use admin;
db.createUser(
{
user: "root",
pwd: "root123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
}
)
show users;
{
_id": "admin.root",
"userId": UUID( "5db3aafd-b1fd-4bea-925e-8a4bfb709f22" ),
"user": "root",
"db": "admin",
"roles": [ {
"role": "userAdminAnyDatabase",
"db": "admin"
},
{
"role": "readWriteAnyDatabase",
"db": "admin"
}
],
"mechanisms": [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
Solution 4:
I have the same problem, and it solved by removing the 'authSource' param
/* Not working */
mongoose.connect("mongodb://localhost:27017/test", {
"auth": { "authSource": "admin" },
"user": "admin",
"pass": "admin123",
"useMongoClient": true
});
/* Working */
mongoose.connect("mongodb://localhost:27017/test", {
"user": "admin",
"pass": "admin123",
"useMongoClient": true
});
Tested on Mongoose-v5.0.0.