node.js - What is the correct way to make Validators with Mongoose -
i had userschema, first email, username , password fields own validators. wanted add more fields bio, location gender , birthday, own 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,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} });
now problem when want register, it's running every validators, of course error occured because in register page i'm not asking bio, location etc ..
i tried adding required:false still not working , didn't find satisfying answer
edit
here's how create new user
router.post('/register',(req,res)=>{ if (!req.body.email) { res.json({success:false,message: 'you must provide e-mail'}); } else{ if (!req.body.username) { res.json({success:false,message:'you must provide username'}); } else{ if(!req.body.password){ res.json({success:false,message:'you must provide 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 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'}) } }); } } } });
the errors biovalidator , gendervalidator.
in fact question is, how choose validator going executed.
edit
in order make work remove required , validators field follows:
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} });
wiki
Comments
Post a Comment