How to retrieve a previously created role, and add another user to it?

cloud

#1

Hi,

Using Realm Cloud Version 3.6.5

I created a new Role named “myOrganization” using the following javascript code

let role = realm.create('__Role', { name: 'myOrganization' });

Now at a later stage, I want to retrieve this Role and add a user whose ID is available using user.retrieveAccount to it. How can I do that?

Looking at the Javascript examples and the API @ https://realm.io/docs/javascript/latest/api/ I am unable to figure that out. Can someone please help with some code snippets?

Thanks,

Anuj


#2

Ok, figured that out.

        // Retrieve user account by provider type and username.  Requires Administrator privileges on logged in user - TODO: Figure out how this will be done in the deployed app without providing an admin account on that deployment.  How will this work when offline?
        user.retrieveAccount('password', 'theOtherUser')
          .then((user) => {
            // retrieve the role and user objects.
            let role = realm.objectForPrimaryKey('__Role', 'myOrganization');
            // console.log causes error on otherUser.
            let otherUser = realm.objectForPrimaryKey('__User', user.user_id);

            realm.write(() => {
              role.members.push(otherUser);
            });
          })
          .catch(err => console.log('Error retrieving account', err));