代码之家  ›  专栏  ›  技术社区  ›  Barry Michael Doyle

如何在Meteor中创建用户时获取用户ID?

  •  5
  • Barry Michael Doyle  · 技术社区  · 9 年前

    我正在使用Meteor启动功能在服务器上创建默认用户。我想创建一个用户,并在启动时验证他/她的电子邮件(我假设只有在创建帐户后才能这样做)。

    以下是我所拥有的:

    Meteor.startup(function() {
      // Creates default accounts if there no user accounts
      if(!Meteor.users.find().count()) {
        //  Set default account details here
        var barry = {
          username: 'barrydoyle18',
          password: '123456',
          email: 'myemail@gmail.com',
          profile: {
            firstName: 'Barry',
            lastName: 'Doyle'
          },
          roles: ['webmaster', 'admin']
        };
    
        //  Create default account details here
        Accounts.createUser(barry);
    
        Meteor.users.update(<user Id goes here>, {$set: {"emails.0.verified": true}});
      }
    });
    

    正如我所说,我假设必须先创建用户,然后才能将已验证的标志设置为true(如果此语句为false,请显示在创建用户时使标志为true的解决方案)。

    为了将电子邮件验证标志设置为true,我知道我可以在创建后使用 Meteor.users.update(userId, {$set: {"emails.0.verified": true}}); .

    我的问题是,我不知道如何获取我新创建的用户的userID,我该怎么做?

    1 回复  |  直到 9 年前
        1
  •  7
  •   Brett McLain    9 年前

    您应该能够访问从帐户返回的用户id。createUser()函数:

    var userId = Accounts.createUser(barry);
    Meteor.users.update(userId, {
        $set: { "emails.0.verified": true}
    });
    

    或者,您可以通过帐户访问新创建的用户。onCreateUser()函数:

    var barry = {
      username: 'barrydoyle18',
      password: '123456',
      email: 'myemail@gmail.com',
      profile: {
        firstName: 'Barry',
        lastName: 'Doyle'
      },
      isDefault: true, //Add this field to notify the onCreateUser callback that this is default
      roles: ['webmaster', 'admin']
    };
    
    Accounts.onCreateUser(function(options, user) {
        if (user.isDefault) {
            Meteor.users.update(user._id, {
                $set: { "emails.0.verified": true}
            });
        }
    });