【问题标题】:How to get user ID during user creation in Meteor?在 Meteor 中创建用户期间如何获取用户 ID?
【发布时间】:2016-01-21 20:06:41
【问题描述】:

我正在使用 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,我知道我可以在创建后使用 Meteor.users.update(userId, {$set: {"emails.0.verified": true}}); 更新用户。

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

【问题讨论】:

    标签: meteor user-accounts creation email-verification


    【解决方案1】:

    您应该能够访问从 Accounts.createUser() 函数返回的用户 ID:

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

    您也可以通过 Accounts.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}
            });
        }
    });
    

    【讨论】:

    • 替代选项运行但验证标志仍然为假。我应该在createUsers 函数之前还是之后运行onCreateUser 函数?目前我正在运行它。
    • 第二种解决方案是在创建帐户时简单地注册一个回调。通过在其中放置一个 console.log() 来验证它是否按预期运行。每当创建新帐户时,该回调中的代码都应该运行,而不仅仅是在这个单一实例中。对于第一个解决方案,我将其修改为不包含回调。
    • 您的第一个新解决方案成功了!谢谢你的时间:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多