Issue
Im totally noob with node. I want to validate if user exist in db and validate if passwords matches to each other. This is what I managed so far :
this is my router
const router = require('express').Router();
let User = require('../models/user.model');
const { check, validationResult } = require('express-validator')
router.route('/').get((req, res) => {
User.find()
.then(users => res.json(users))
.catch(err => res.status(400).json('Error: ' + err));
});
router.route('/add').post([
check('username', "min 5").isLength({ min: 5 }).custom(value => {
return User.findOne({
where: {
username: value
}
}).then(user => {
if (user) {
throw new Error('user exist');
}
});
}),
check('password', "cant be empty").isLength({ min: 8 }),
],(req, res) => {
const errors = validationResult(req)
if (!errors.isEmpty()) {
res.json("fields cant be empty")
}
if(req.body.password2 !== req.body.password) {
res.json("passwords dont match")
}
const user = {
username: req.body.username,
password: req.body.password,
}
const newUser = new User(user);
newUser.save()
.then(() => res.json('User added!'))
.catch(err => res.status(400).json('Error: ' + err));
});
module.exports = router;
and this is my submit function on client side
onSubmit(e) {
e.preventDefault();
const user = {
username: this.state.username,
password: this.state.password,
password2: this.state.password2
}
axios.post('http://localhost:5000/users/add', user)
.then(res => console.log(res.data))
this.setState({
username: ''
})
}
This works somehow but I’d like to do in proper way. I appreciate any tips how can I achieve this and how can I handle errors in proper way.
Solution
You can use mongoose buit-in validators for that.all schemaType have some in built validators.
const userSchema=new mongoose.Schema({
name:{
type:String,
required:[true,'Please provide user name'],
minlength:5
},
email:{
type:String,
required:[true,'Please provide email'],
unique:true,
validate:[validator.isEmail,'Please provide a valid email']
},
password:{
type:String,
required:[true,'Please provide password'],
minlength:8,
},
confirmPassword:{
type:String,
validate:{
validator:function(el){
return el===this.password;
},
message:'Passwords are not same!'
}
}
});