What is the correct syntax for creating a user and populating the role?

System Information
  • 4.x:
  • MySQL:

Hi,

I am trying to create a user (table: up_users) and set the role, but the role is not set. What is the correct syntax to set the role?

I have tried the following:

const entry = await strapi.entityService.create('plugin::users-permissions.user', {
	data: { username: name, email: email, provider: 'local', password: pwd_hash, confirmationToken: null, confirmed: false, blocked: false, },
	populate: {
		role: {
			where: {
				type: 'user'
			}
		},
	}
})
const entry = await strapi.entityService.create('plugin::users-permissions.user', {
	data: { username: name, email: email, provider: 'local', password: pwd_hash, confirmationToken: null, confirmed: false, blocked: false, },
	populate: {
		role: {
			type: 'user'
		},
	}
})
const entry = await strapi.db.query('plugin::users-permissions.user').create({
	data: { username: name, email: email, provider: 'local', password: pwd_hash, confirmationToken: null, confirmed: false, blocked: false, },
	populate: {
		role: {
			where: {
				type: 'user'
			}
		},
	},
})

I also found the following page in the Strapi documentation (https://docs.strapi.io/developer-docs/latest/developer-resources/database-apis-reference/entity-service/components-dynamic-zones.html#creation), but it doesn’t get me anywhere either.

Here is what I am doing in my unit tests

const users = [
  { username: "authenticated", email: "authd@test.com", provider: "local", password: "test1234", role: "authenticated" },
  { username: "contributor", email: "contrib@test.com", provider: "local", password: "test1234" , role: "contributor" },
];

async  function createUsers(strapi){
  await Promise.all(
    users.map(async (user) => {
      // fetch role by type to get ID
      if ( user.role) {
        const foundRole = await strapi.query("plugin::users-permissions.role").findOne({where: {type: user.role}});
        if (!foundRole) throw Error(`role ${user.role} does not exist`);
        user.role = foundRole.id;
      }
      const { id } = await strapi.plugins['users-permissions'].services.user.add({
        ...user,
        blocked: false,
        confirmed: true,
        created_by: 1, //user admin id
        updated_by: 1, //user admin id
      });
      // Mutate user add jwt for later..
      user.jwt =  await strapi.service('plugin::users-permissions.jwt').issue({ id })
      }
  ));
}

FYi the user.add service seems to properly hash the password as well.

This has been a help.

I am looking to give a role permissions. I have tons of collections I would like a role to have access to but I cant see a way to do this.