【发布时间】: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 提供密码
-
请让我知道您是否能够通过新的更新做到这一点