我是NodeJS的新手,并编写了一个创建新用户的方法,但我需要验证传递的参数。我正在尝试确保电子邮件未注册两次。这不起作用,因为它在self.emailExists()回调完成之前检查错误数组是否为空,我该如何解决这个问题?
userSchema.statics.buildUser = function(email, name, cb) {
var self = this;
var user = new this();
var errors = [];
if (!validator.isEmail(email)) {
errors.push({
'err': -1,
'msg': 'Invalid email'
});
} else {
self.emailExists(email, function(exists) {
if (exists) {
errors.push({
'err': -1,
'msg': 'Email address is already in use'
});
} else {
user.email = email;
}
});
}
if (!validator.trim(name).length > 0) {
errors.push({
'err': -1,
'msg': 'Invalid name'
});
} else {
user.name = name;
}
if (errors.length != 0) {
cb(errors, null);
} else {
cb(false, user);
}
}
我的emailExists方法是:
userSchema.statics.emailExists = function(email, cb) {
var self = this;
self.count({email: email}, function (err, count) {
cb(count > 0);
});
}