0
我是新來的NodeJS,並且寫了一個方法來創建一個新用戶,但我需要驗證傳遞的參數。我試圖確保電子郵件沒有註冊兩次。這不起作用,因爲它在self.emailExists()回調完成之前檢查錯誤數組是否爲空,我該如何解決這個問題?節點JS驗證
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);
});
}