如何检查用户的电子邮件(电子邮件[0].address)是否已存在,然后再尝试使用它来更改其他用户的电子邮件



我有一个更改用户地址的方法(每个用户只有一个地址,所以emails[0].address)。

在该方法中,如果另一个用户具有相同的emails[0].addressAccounts.addEmail(this.userId, newemail);精细地阻止添加。我在客户中收到了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)。

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

在我的方法下面。

谢谢

// 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, setted to verified:false
        Accounts.addEmail(this.userId, newemail);
        // Send email verification to the new email address
        Accounts.sendVerificationEmail(this.userId, newemail);
        return true;
    }
});

您可以直接更新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}}});
  }
});

最新更新