在尝试使用用户的电子邮件 (emails[0].address) 更改其他用户的电子邮件之前,如何检查该用户的电子邮件是否已存在?

问题描述 投票:0回答:1

我有一种方法可以更改用户的地址(每个用户只有一个地址,所以是

emails[0].address
)。

在该方法中,如果其他用户有相同的内容,则

Accounts.addEmail(this.userId, newemail);
会精细地阻止添加
emails[0].address
。我在客户那里收到了
error.reason === 'Email already exists.'
太棒了。

但是在致电

Accounts.addEmail(this.userId, newemail);
之前,我需要致电
Accounts.removeEmail(this.userId, emailold);
,他将删除旧地址并为
emails[0].address
免费留下
Accounts.addEmail(this.userId, newemail);
(当帐户中没有电子邮件地址时,默认情况下可以很好地使用
emails[0].address 
)。

那么,如果

Accounts.removeEmail(this.userId, emailold);
被任何其他用户用作
newemail
,我该如何处理和停止
emails[0].address

以下是我的方法。

谢谢

// Change Email Address of the User
Meteor.methods({
    addNewEmail: function(emailold, newemail) {
        
        // this function is executed in strict mode
        'use strict';
        
        // Consistency var check
        check([emailold, newemail], [String]);
        
        // Let other method calls from the same client start running,
        // without waiting this one to complete.
        this.unblock();

        //Remove the old email address for the user (only one by default)
        Accounts.removeEmail(this.userId, emailold);
        //Add the new email address for the user: by default, set to verified:false
        Accounts.addEmail(this.userId, newemail);
        // Send email verification to the new email address
        Accounts.sendVerificationEmail(this.userId, newemail);
        
        return true;
    }
});
meteor
1个回答
1
投票

您可以直接更新

users
集合,并自行处理任何错误。这就是我所做的:

Meteor.methods({
  "users.changeEmail"(address) {
    check(address, String);

    const existingAddressCheck = Meteor.users.findOne({"emails.0.address": address});

    if(existingAddressCheck) {
      if(existingAddressCheck._id === Meteor.userId()) {
        throw new Meteor.Error("users.changeEmail.sameEmail", "That's already your registered email address!");
      } else {
        throw new Meteor.Error("users.changeEmail.existing", "An account with that address already exists");
      }
    }
    return Meteor.users.update({_id: Meteor.userId()}, {$set: {"emails.0": {address, verified: false}}});
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.