节点JS验证

时间:2015-10-21 02:27:06

标签: javascript node.js

我是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);
    });

}

1 个答案:

答案 0 :(得分:0)

您需要重新构建代码以将errors.length检查放入emailExists()回调中。尝试使用Async.js和Promises来更好地管理异步调用