6

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.

1

2 Answers 2

7

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.