node.js - 通过回调或 Mongoose 模型验证 PassportJS?

标签 node.js validation mongoose passport.js

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

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
        },
    }
});

推荐其中哪一个,为什么?

最佳答案

为什么不两者都做呢?如果只使用第二个,将很难显示该消息

email address already exists

因为您需要捕获重复键错误索引,然后在注册时显示错误消息。相反,您可以检查电子邮件地址是否已存在(这是更明确的),并在注册时同时使用唯一索引显示相应的错误消息,以确保电子邮件地址没有重复的条目。

关于node.js - 通过回调或 Mongoose 模型验证 PassportJS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24502129/

相关文章:

javascript - Mongoose -> findOne -> 排序 -> 如果数据库中没有记录

mongodb - Mongoose 更新: Increment a counter and reset to 0 on a new date

node.js - Nodejs/Express API 的简单 Mocha/Chai 测试

node.js - 为什么 Angular 8 推荐 Node 12?

node.js - MongoDB 中的慢速查询,使用组进行集合范围的聚合查询

c# - 具有多个参数的自定义验证属性

javascript - 验证文本框,以便必须输入值

regex - Laravel - 使用正则表达式仅验证字母、数字和空格

node.js - 创建 ionic 项目失败?

node.js - Mongoose .save() -- TypeError : _this[i]. 发出不是一个函数