【问题标题】:Route using wrong validator in Mongoose在 Mongoose 中使用错误的验证器进行路由
【发布时间】:2017-08-23 02:22:43
【问题描述】:

我正在使用 Postman 测试路由,这条路由在user.save((err)=>{}) 说密码太长之后返回错误消息。它使用了我创建的passwordValidator,但我显然没有在 Schema 中为这条路线调用它。

我做错了什么?

猫鼬中的用户架构:

    const userSchema=new Schema({
    email: { type: String, required: true, unique: true, lowercase: true, validate: emailValidators},
    username: { type: String, required: true, unique: true, lowercase: true, validate: usernameValidators},
    bio: { type:String,default:null,validate:bioValidators},
    location: {type:String, default:null},
    gender: {type:String,default:null,validate:genderValidators},
    birthday: { type:String,default:null},
    password: { type: String, required: true,validate: passwordValidators}
});

路线:

router.put('/editProfile',(req,res)=>{
        if(!req.body.bio){
            res.json({success:false,message:"No bio provided"});
        }
        else{
            if(!req.body.location){
                res.json({success:false,message:"No location provided"});
            }
            else{
                if(!req.body.gender){
                    res.json({success:false,message:"No gender provided"});
                }
                else{
                    if (!req.body.birthday) {
                        res.json({success:false,message:"No birthday provided"});
                    }
                    else{
                        User.findOne({_id:req.decoded.userId},(err,user)=>{
                            if(err){
                                res.json({success:false,message:"Something went wrong: "+err});
                            }
                            else{
                                if(!user){
                                    res.json({success:false,message:"User not found"});
                                }
                                else{
                                    user.bio=req.body.bio;
                                    user.location=req.body.location;
                                    user.gender=req.body.gender;
                                    user.birthday=req.body.birthday;
                                    user.save((err)=>{
                                        if(err){
                                            res.json({success:false,message:'Something went wrong: '+ err}); //returns this
                                        }
                                        else{
                                            res.json({success:true,message:"Account updated !"});
                                        }
                                    }); 
                                }
                            }
                        });
                    }
                }
            }
        }
    });

编辑

这是密码验证器数组

const passwordValidators = [
    {
        validator: passwordLengthChecker,
        message: 'Password must be at least 5 characters but no more than 40'
    },
    {
        validator:validPassword,
        message: 'Must have at least one uppercase, lowercase, special character, and number'
    }
];

还有跳棋

let passwordLengthChecker = (password)=>{
    if (!password) {
        return false;
    }
    else{
        if(password.length<5 || password.length>40){
            return false;
        }
        else{
            return true;
        }
    }
};

let validPassword = (password)=>{
    if (!password) {
        return false;
    }
    else{
        const regExp = new RegExp(/^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[\d])(?=.*?[\W]).{8,35}$/);
        return regExp.test(password);
    }
};

如您所见,它使用了 passwordLengthChecker,尽管它不应该

编辑 N°2

我刚刚意识到我在架构下方有这个中间件

userSchema.pre('save', function(next){
    if(!this.isModified('password'))
    return next();

    bcrypt.hash(this.password, null, null, (err,hash)=>{
        if(err) return next(err);
        this.password=hash;
        next();
    });
});

这是否意味着每次我使用 save() 时都会运行这个函数?

【问题讨论】:

  • validate: passwordValidators 这不是问题吗?你在使用什么密码验证器?你能给我们看看吗?
  • 这里是验证器
  • 请检查答案。您忘记为用户@Azoulay Jason 提供密码
  • 请让我知道您是否能够通过新的更新做到这一点

标签: node.js mongodb mongoose


【解决方案1】:

问题出在这里,您提供了biolocationgenderbirthday,但没有提供密码。当您不声明密码时,其length 将等于0。这就是你得到错误的原因。长度可以从540

else{
                                    user.password=req.body.password;
                                    //I added user.password here, this is what you should do
                                    user.bio=req.body.bio;
                                    user.location=req.body.location;
                                    user.gender=req.body.gender;
                                    user.birthday=req.body.birthday;
                                    user.save((err)=>{
                                        if(err){
                                            res.json({success:false,message:'Something went wrong: '+ err}); //returns this
                                        }
                                        else{
                                            res.json({success:true,message:"Account updated !"});
                                        }
                                    }); 
                                }

在此更新

如果您只打算更新bio,location,genderbirthday,那么使用save() 函数是错误的。你需要使用findOneAndUpdate()函数。

User.findOneAndUpdate({_id:req.decoded.userId}, { $rename : {gender: 'male' , bio : 'somethingElse'}}, {new: true}, function(err, user){
if(err) throw err;
else{
console.log("done : " + user.gender);
}
});

另请参阅 findOneAndUpdate its operators to be used

【讨论】:

  • 感谢您的回答,这就是我最初的想法,所以我尝试了这个解决方案,但是由于密码是加密的,它不适合密码验证器。我认为这里真正的问题是它运行每个验证器,我找不到解决这个问题的解决方案
  • @AzoulayJason 那你需要修改配置,加密前需要检查长度!
  • post请求之后的后端服务器中,首先检查用户输入 req.body.password的长度,然后执行进度。你的配置是错误的@AzoulayJason
  • 是的,但是在这个阶段,除非我再次询问他,否则我无法获得当前用户的未加密密码!我必须找到运行正确验证器的方法,我见过同步猫鼬验证器,这可能是解决方案
  • 这不是我从 => /editProfile 获得的个人资料编辑页面。这是更改密码的页面吗?如果是这样,请在将文本实施到数据库之前检查用户输入
【解决方案2】:

所以我认为 bcrypt 函数破坏了 Mongoose save() 函数, 我现在在 Mongoose 文档中找到了另一个解决方案。

User.findByIdAndUpdate(req.decoded.userId,{$set:{bio:req.body.bio, location:req.body.location, gender:req.body.gender, birthday:req.body.birthday}},{new:true},function(err,user){
                            if(err){
                                res.json({success:false,message:"Something went wrong: "+err});
                            }
                            else{
                                if(!user){
                                    res.json({success:false,message:"User not found"});
                                }
                                else{
                                    res.json({success:true,user:user});
                                }
                            }
                        });

【讨论】:

    猜你喜欢
    • 2017-05-05
    • 1970-01-01
    • 1970-01-01
    • 2018-04-28
    • 2013-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-02
    相关资源
    最近更新 更多