Very confused with "db" fields when creating a user-defined role

Hi all,

I can’t get my head around when following the Create User with User-defined Role lesson.

First of all, if we look at how a role is associated with a user regarding a specific database, we know we need to do …

> use admin
> db.createUser({ user: "name", pwd: "pwd", roles: [ { role: "read", db: "nasa" } ]}) // This line means the user has "read" role for "nasa" db.

However, if we recall what a role has in terms of privileges, the privileges have already specified which resources the role can or can’t do with. For example …

> use admin
> db.createRole({ role: "aRole", roles: [], privileges: [ { resource: {db: "some_other_db", collection: "random_collection"}, actions: ["find"]}] })

As far as I understand, the role definition above means the role can only run “find” on “some_other_db”.“random_collection”.

Now if I create a user with role but for “nasa” database like this …

> use admin
> db.createUser({ user: "another_user", pwd: "pwd", roles: [ { role: "aRole", db: "nasa" } ]}) 

What does this mean? Suddenly the resources defined on the role privileges get overridden or the db:"nasa" option in the createUser command has no effect? To me, having the “db” in two places is conflicting and confusing.

After researching on the manual, I think my understanding on the roles document of the createUser command is wrong from the very beginning although this course or any other courses didn’t say it clearly or explicitly either.

> db.createUser({ user: "name", pwd: "pwd", roles: [ { role: "read", db: "nasa" } ]})

The db field in the role document is actually about where the role read is from, rather than about which db the role read is applied to.

role: "read", db: "admin" and role: "read", db: "nasa" are effectively different roles, which can be verified by using getRole on admin db and nasa db respectively.

If it’s the case, which I believe so now, then I have no confusion, but I wish the course has said this clearer.

Hi waynesi

Yes, with the createUser method the db key value in the roles document really does seem to provide a different function depending whether the role is Built-In verses User-Defined.

For me the key to understanding the different behavior is to keep in mind whether you are using a Built-In or User-Defined role.

read is a Built-In role and the db value is where the privileges are applied to.

For a User-Defined role where the privileges are applied to (action and resource) is defined in the role definition.

So in the createUser command when granting a User-Defined role to a user the db value is used to locate the User-Defined role.

hope that helps,