tramore925
tramore925

Reputation: 21

Can't connect Mongoose to MongoDB with authentication

I created a user with readwrite role for MongoDB database myDatabase.

After starting MongoDB server with --auth, in Mongo shell:

mongo -u userName -p userPassword --authenticationDatabase myDatabase

Connects properly and can read/write myDatabase

In mongoose tried to connect to MongoDB using

mongoose.connect('mongodb://localhost/myDatabase', {user:'userName', password:'userPassword'});

Also

mongoose.connect('mongodb://localhost/myDatabase', {user:'userName', password:'userPassword', {auth: {authdb:'myDatabase'}});

Able to connect to myDatabase but get authorization error when read/write

MongoError: not authorized for query on myDatabase.myCollection

How can I fix this?

Upvotes: 2

Views: 5126

Answers (2)

Alexander Elgin
Alexander Elgin

Reputation: 6956

You should specify the auth database. Your second attempt was almost correct but instead of authdb you should use authSource options. In your case it should be

mongoose.connect('mongodb://localhost/myDatabase', {user:'userName', password:'userPassword', {auth: {authSource:'myDatabase'}});

Upvotes: 1

Lisa Gagarina
Lisa Gagarina

Reputation: 693

I would suggest to try the following:

1) Connect with string URI format https://docs.mongodb.org/manual/reference/connection-string/

2) Which version of mongoose are you using? According to the docs http://mongoosejs.com/docs/connections.html you should provide 'pass' property but you are passing it as 'password'.

Upvotes: 3

Related Questions