aripian
aripian

Reputation: 85

Authentication error when connecting to specific mongodb database

I am currently using nodejs with mongodb native driver. So my mongodb has been set with admin auth with root role, so I can log in using robomongo or command line just fine. So back to my project, I m able to connect to mongodb just fine if i set my connection string:

mongodb://admin:password@localhost:27017/

However, if I use this connection string:

mongodb://admin:password@localhost:27017/specificdb

It return as:

MongoError: Authentication failed

I am able to access the db using command and robomongo, is there anything I can do? I have added the admin user under the db, but still got the same problem.

Upvotes: 5

Views: 3011

Answers (2)

Khmiri Mohamed Khalil
Khmiri Mohamed Khalil

Reputation: 136

this worked for me :

first solution on connection :

mongoose.connect('mongodb://....', {
// add this line 
authSource:"admin",
....
})

or second solution add to the uri "?authSource=admin" :

mongodb://user:password@host/yourDB?authSource=admin

** to note that I am using mongoose and this is the documentation specefic statement and the url :

authSource - The database to use when authenticating with user and pass. In MongoDB, users are scoped to a database. If you are getting an unexpected login failure, you may need to set this option.

https://mongoosejs.com/docs/connections.html#options

Upvotes: 4

p.streef
p.streef

Reputation: 3815

The database you specify is the one you authenticate on. If the user is not known/has no roles for that database it cannot authenticate to it.

https://docs.mongodb.com/manual/reference/connection-string/

What you can do is either create the (or a new) user for that database or use an authentication database parameter.

Upvotes: 2

Related Questions