我有一种方法可以更改用户的地址(每个用户只有一个地址,所以是
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;
}
});
您可以直接更新
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}}});
}
});