如何为我的 Meteor 应用程序中的第一个用户分配特定角色?

How can I assign the first user in my Meteor app a specific role?

我正在使用 meteor-roles 权限,我想为第一个创建的用户添加一个特定的角色。我知道我不能在 onCreateUser 挂钩中使用 addUsersToRoles,因为它会在数据库中查询用户 ID,但用户尚未添加到数据库中。

我发现 this answer 建议包装 createUser 方法,但这对我不起作用。服务器抱怨 createUser 还不支持回调。

你可以在 OnCreateUser 上做这样的事情。

Accounts.onCreateUser(function(options, user) {
    //if there is not users on the database
    //we assign the First-User role
  if(Meteor.users.find().count() === 0){ 
     user.role = "First-User"
  }else{
     user.role = "normalUser"
   }
  return user;
});

假设您拥有 First-user 角色。像这样。

Meteor.publish("First-User", function () {
  var user = Meteor.users.findOne({_id:this.userId});

  if (Roles.userIsInRole(user, ["First-User"])) {
    return Meteor.users.find({}, {fields: {emails: 1, profile: 1, roles: 1}});
  } 

  this.stop();
  return;
});

请记住,您应该在 createUsers 方法的顶部调用 onCreateUser

Note that the Roles.addUsersToRoles call needs to come after Accounts.createUser or Accounts.onCreate or else the roles package won't be able to find the user record (since it hasn't been created yet)

来自 README.

希望这有效。