【问题标题】:Meteor: Adding Fields on createAccountMeteor:在 createAccount 上添加字段
【发布时间】:2013-12-13 22:31:50
【问题描述】:

我正在尝试使用 Meteor 角色包:https://github.com/alanning/meteor-roles 显然要在用户模型中创建一个新字段。

用户创建没有问题,但我试图定义的“角色”字段没有创建。我也可以在其中添加“个人资料”和详细信息。但由于某种原因,我无法创建角色字段。这是我的表格:

Template.signup.events({
 'submit #signup-form' : function(e, t) {
   e.preventDefault();
   var roles = ['admin'],
       email = t.find('#email').value,
       password = t.find('#password').value;

   Accounts.createUser({email: email, password : password, roles: roles}, function(err){
       if (err) {
         alert("User Not Added")
       } else {
         console.log("User Added.")
       }

   });

 }
});

最终我需要将其发布给客户端,但现在我只想在 MongoDb 中显示该字段,但事实并非如此。

三件事:

  1. 我觉得上面的代码应该可以工作,但我显然遗漏了一些东西
  2. 在包文档中提到了这个Roles.addUsersToRoles,我 试过但没有运气
  3. 或者我是否需要在创建记录后更新它?

我确实进入了数据库并手动添加了字段和关联的字符串来更新它(使用 $set)并且它起作用了。但是从表格本身来看,没有运气。

任何指针将不胜感激。谢谢。

【问题讨论】:

    标签: javascript mongodb meteor


    【解决方案1】:

    Accounts.createUser 函数只允许您通过 profile 选项添加任意用户属性,这是它们最终存储在 mongo 中的位置。这就是为什么 Meteor 忽略了您的 Accounts.createUser 调用中的 roles: roles 部分。

    meteor-roles 包确实将分配给用户的角色列表直接存储在 users 集合中,但这几乎只是一个实现细节,您最好还是坚持使用 meteor-roles 提供的 API用于将用户添加到角色:

    Roles.addUsersToRoles(<userId>,[<list of roles>])

    传递给Roles.addUsersToRolesuserIdAccounts.createUser 在服务器上调用时返回的值,这可能是您想要执行此操作的地方,因为这样感觉更安全。

    【讨论】:

    • 说得很好。谢谢你。对于遵循此规则的任何人,请勿使用 userId 作为 Roles.addUserToRoles 上的变量名。 go-oleg 没有说,我只是这样做是因为它有意义。但是,这是在某处保留的,即使我已经正确设置了所有内容,但在我更改名称之前它还是无法正常工作,
    • @go-oleg 很到位。 github repo 中的示例应用程序显示了这一点:github.com/alanning/meteor-roles/blob/master/examples/…
    【解决方案2】:

    Accounts.createUser 函数仅将usernameemailpasswordprofile 作为用户对象的参数。 See the documentation here. 所以,要向新的用户对象添加另一个字段,您需要在第二步中添加它:

    var uid = Accounts.createUser({email: email, password: password});
    Meteor.users.update(uid, {$set: {roles: roles}});
    

    【讨论】:

    • Hubert OG 你是个球手。到处都能看到你的回答,谢谢。如果用户愿意,我将使用此信息允许用户添加到他们的个人资料中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-07
    • 1970-01-01
    • 2014-06-23
    • 1970-01-01
    • 1970-01-01
    • 2015-02-12
    • 1970-01-01
    相关资源
    最近更新 更多