Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a user in MongoDB v3.0.5

I need to create a user for my database in mongodb, but it seems that I can't get it to work.

I have installed mongoDb v3.0.5 on my windows 7 machine. according to this article, I connected to my mongo instance using:

mongo -u siteUserAdmin -p password

and then I created first user via:

use admin
db.createUser(
  {
    user: "siteUserAdmin",
    pwd: "password",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)

then I created a user for my nodejs application on exampleDb:

use admin
db.createUser(
  {
    user: "myUser",
    pwd: "123456",
    roles: [ { role: "readWrite", db: "exampleDb" } ]
  }
)

and finally in my nodejs application, when I try to connect to my mongo instance using this connection string:

var connString = "mongodb://myUser:[email protected]:27017/exampleDb";

an Authentication failed error happens:

{ name: 'MongoError',
  message: 'Authentication failed.',
  ok: 0,
  code: 18,
  errmsg: 'Authentication failed.'
}
like image 858
Nasser Torabzade Avatar asked Sep 28 '22 00:09

Nasser Torabzade


1 Answers

When you "use admin", your new user is created in database "admin".

use admin
db.createUser(
  {
    user: "myUser",
    pwd: "123456",
    roles: [ { role: "readWrite", db: "exampleDb" } ]
  }
)

So your connection string must be as:

var connString = "mongodb://myUser:[email protected]:27017/admin";
like image 75
Majid Yaghouti Avatar answered Dec 24 '22 05:12

Majid Yaghouti