How to add extra user roles with alanning:roles


#1

Here’s my user document

{
"_id" : "3WWWNiGh5Z74Tgxbx",
"createdAt" : ISODate("2016-05-21T14:41:37.300Z"),
"services" : {
	"password" : {
		"bcrypt" : "$2a$10$NPaHXZzCXIyloKv.cK0t6uZDGmnQeGRJZ9W45dHo.EeZ/HMtEfDLq"
	},
	"resume" : {
		"loginTokens" : [
			{
				"when" : ISODate("2016-05-22T03:06:10.741Z"),
				"hashedToken" : "v4z3xtblqtwipuBIJx4gEj1/tvJxVa+56jcfPrNcJto="
			}
		]
	}
},
"emails" : [
	{
		"address" : "test2@test2.com",
		"verified" : false
	}
],
"roles" : [
	"normal-user"
]

}

This user already has the role “normal-user”. What I want to do is add the user role “host” for this user when ever the user decides to become a host. Here’s what I did,

Roles.setUserRoles(_userId, ['normal-user','host']);

I just get the feeling that this is not the correct way to do this as this will remove the existing user role (“normal-use”) and reassign the same.

I just need to know if there’s a recommended/correct way to do this.


#2

You have two methods in the API: addUsersToRoles() and setUserRoles().
As they are both in the API documentation, they are both recommended and they both work.
There is no point in getting “the feeling that this is not the correct way” :slight_smile:

(And by the way, a Mongo update( { $set: ... } ) is atomic [definition] up to the document level, so saying that “this will remove the existing user role” is not correct. Before the set operation the user will have one role, and after he will have two. There is no state between these two.)


#3

Thanks @jesperwe. I’m still a newbie, trying to wrap my head around this. This helps a lot.