通过回调或Mongoose模型验证PassportJS?

时间:2014-07-01 03:39:58

标签: node.js validation mongoose passport.js

我正在设置注册和登录用户身份验证的护照。现在我看到我可以通过回调验证信息,但是我也可以验证用户模型中的信息。例如,如果我想要使电子邮件字段成为必需,那么我可以执行以下操作:

使用Passport验证

// Create the local sign up with Passport
passport.use('local-signup', new LocalStrategy({
        usernameField : 'userEmail', // Email Field
    passwordField : 'userPassword', // Password Field
    passReqToCallback : true
    },
    function(req, email, password, done) {

        // Find a user with this email
        User.findOne({ "local.email": email }, function(err, user) {

            if (err) throw err;

            // If a user with this email already exists, continue with failureRedirect
            if (user) {
                return done(null);

            } else {
                // Otherwise create a new user with the email and generate a hashed password
                User.create({
                    local: {
                        email: email
                    }
                }, function(err, user) {
                    if (err) throw err;

                    user.local.password = user.generateHash(password);

                    // Return the user and finish! :)
                    return done(null, user);
                });
            }
        });
    };
}));

使用用户模型

var userSchema = new Schema({
    local: {
        email: {
            type: String,
            unique: true // Make it unique! Handles entire validation
        },
        password: {
            type: String
        },
    }
});

推荐哪一个以及为什么?

1 个答案:

答案 0 :(得分:1)

为什么不两者兼而有之?如果仅使用第二个,则很难显示消息

  

电子邮件地址已存在

因为您需要捕获duplicate key error index然后在注册时显示错误消息。而不是你可以检查,如果已经存在更明确的电子邮件地址并在使用唯一索引同时在注册时显示相应的错误消息,将确保没有重复的电子邮件地址条目。