Reputation: 796
I'm rather new to Linux, NodeJs and MongoDB but I setup a Linux Server running a MongoDB (db version v4.0.16).
I added two users like this. One called mongo-admin and one called mongo-root.
# mongo
> use admin
> db.createUser({
user: "mongo-admin",
pwd: "myAwesomePassword",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
})
> db.createUser({
user: "mongo-root",
pwd: "myAwesomePassword",
roles: [ { role: "root", db: "admin" } ]
})
I then enabled authentication in /etc/mongod.conf like this
security:
authorization: "enabled"
On my development Machine I setup a little NodeJS script that tries to connect to the server using mongoose, and simply add a document there.
Now the situation is very strange. If I use mongodb://mongo-root:[email protected]:27017
as a connectionstring, everything works fine and a new DB named test
is created and the document is added. But as soon as I add a /mydatabasename
at the end of the string, mongoose will suddntly time out after 30 seconds of trying to connect.
If I connect to MongoDB using a Software called Robo3T, I can connect just fine, and I also have the rights to create a new database just fine.
I also checked the /etc/log/mongod.log
and found this error:
2020-02-05T07:40:22.006+0000 I ACCESS [conn27] SASL SCRAM-SHA-1 authentication failed for mongo-root on mydatabasename from client 101.101.101.101:51270 ; UserNotFound: Could not find user mongo-admin@mydatabasename
This is the way I connect to the DB
mongoose.connect(
"mongodb://mongo-root:[email protected]:27017/mydatabasename",
{
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
}
);
It seems like mongodb is looking for the user in the database that should be created instead of in the admin db.
Upvotes: 0
Views: 46
Reputation: 59456
Check Connection String URI Format
mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[database][?options]]
/database
Optional. The name of the database to authenticate if the connection string includes authentication credentials in the form of username:password@. If /database is not specified and the connection string includes credentials, the driver will authenticate to the admin database. See also authSource.
authSource
Specify the database name associated with the user’s credentials. authSource defaults to the database specified in the connection string.
Actually the documentation is not 100% correct for this point, the connection string must be like this:
mongodb://mongo-root:[email protected]:27017/mydatabasename?authSource=admin
Upvotes: 1