我有一个userSchema,首先是电子邮件,用户名和密码字段以及他们自己的验证器。 然后我想添加更多字段,如生物,位置性别和生日,以及他们自己的验证器。
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},
password: { type: String, required: true,validate: passwordValidators},
bio: { type:String,required:false,default:null,validate:bioValidators},
location: {type:String,required:false, default:null},
gender: {type:String,required:false,default:null,validate:genderValidators},
birthday: { type:Date,required:false,default:null}
});
现在的问题是,当我想注册时,它会运行每个验证器,所以当然会发生错误,因为在注册页面中我甚至没有要求生物,位置等。
我尝试添加必需的:false但仍然无效,我没有找到任何令人满意的答案
修改
以下是我如何创建新用户
router.post('/register',(req,res)=>{
if (!req.body.email) {
res.json({success:false,message: 'You must provide an e-mail'});
}
else{
if (!req.body.username) {
res.json({success:false,message:'You must provide a username'});
}
else{
if(!req.body.password){
res.json({success:false,message:'You must provide a password'});
}
else{
let user= new User({
email: req.body.email.toLowerCase(),
username: req.body.username.toLowerCase(),
password: req.body.password
});
user.save((err)=>{
if (err) {
if (err.code === 11000) {
res.json({success:false,message:'Username or e-mail already exists'});
}else{
if (err.errors) {
if (err.errors.email) {
res.json({success:false, message:err.errors.email.message});
}
else{
if (err.errors.username) {
res.json({success:false,message:err.errors.username.message});
}
else{
if (err.errors.password) {
res.json({success:false,message:err.errors.password.message});
}
else{
res.json({ success:false,message:err});
}
}
}
}else{
res.json({success:false,message:'Could not save user :', err});
}
}
}
else{
res.json({success:true,message:'Account registered'})
}
});
}
}
}
});
我得到的错误是bioValidator和genderValidator。
实际上我的问题是,我如何选择将要执行哪个验证器。
答案 0 :(得分:2)
编辑
为了使其工作,只需删除required和validators字段,如下所示:
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},
password: { type: String, required: true,validate: passwordValidators},
bio: { type:String, default:null},
location: { type:String, default:null},
gender: { type:String, default:null},
birthday: { type:Date, default:null}
});