Reputation: 331
I am new to node, express wanted a help regarding validation.I am able to validate the data corresponded to post method but for put method the data is not able to get validated.What should be done for the data to get validated in put method?
Below is the user Model
const userSchema = new Schema({
name: {
type: String,
minlength: 3,
required: true,
validate:{
validator:function(value){
return value.length >=3
},
msg:function(){
return 'name is less than 3 characters'
}
}
},
const User = mongoose.model('User', userSchema)
module.exports = User
Below is the controller for user
const express = require('express')
const router = express.Router()
const Customers = require('../model/customers')
router.get('/', (req, res) => {
Customers.find()
.then((customer) => {
res.json(customer)
console.log(customer)
})
.catch(err => res.send(err))
})
router.post('/', async (req, res) => {
let customerData = new Customers({
name: req.body.name,
email: req.body.email,
mobile: req.body.mobile
})
await customerData.save()
.then((customer) => {
res.json(customer)
console.log('customer is....', customer)
})
.catch(err => res.send(err))
})
router.put('/:id', async (req, res) => {
let apiId = req.params.id
const customerData = await Customers.findByIdAndUpdate(apiId,
{
name: req.body.name,
email: req.body.email,
mobile: req.body.mobile
})
if (customerData) {
res.json(Object.assign(customerData, req.body))
}
else {
res.status(404).send('Url did not respond')
}
})
router.delete('/:id', async (req, res) => {
let apiId = req.params.id
const customerData = await Customers.findByIdAndRemove(apiId)
if (customerData) {
res.send(customerData)
}
else {
res.status(404).send('Url did not respond')
}
})
module.exports = { customerController: router }
Upvotes: 0
Views: 240
Reputation: 1682
As per mongoose docs
Mongoose also supports validation for update(), updateOne(), updateMany(), and findOneAndUpdate() operations. Update validators are off by default - you need to specify the runValidators option
So you have to set runValidators: true
Customers.findByIdAndUpdate(apiId,
{
name: req.body.name,
email: req.body.email,
mobile: req.body.mobile
}, { runValidators: true } )
Upvotes: 2