Hy, I'm new in nodeJS. I am stuck at updating a single entity of document. I'm updating the whole document easily but can't able to update a single value. code
router.patch("/:id", async (req, res) => {
console.log(req.params.id);
// check valid student
let student = await Student.findById(req.params.id);
if (!student) return res.status(400).send("Student Not Found");
// validition
// const { error } = validate(req.body);
// if (error) return res.status(400).send(error.details[0].message);
// update the student
student = await Student.updateOne({_id:req.params.id},{$set: req.body});
if(!student) return res.status(404).send('The student record not Updated')
res.status(200).send('Student Record Updated')
});
Validation Function
function validateStudent(student){
const schema = Joi.object({
name:Joi.string().min(3).max(50).required(),
fatherName:Joi.string().min(3).max(50).required(),
email:Joi.string().min(5).max(50).required().email(),
class:Joi.number().min(9).max(12).required(),
fee:Joi.number().min(4000).max(10000).required(),
address:Joi.string().min(1).max(255).required(),
phone:Joi.string().min(1).max(255).required(),
})
return schema.validate(student)
}
Now It's updating my single value in DB but without validation, because if I uncomment the validation then it forces for all required field. How I can validate and update a single value which coming in API from the frontend?
To update single field like email
student = await Student.updateOne({_id:req.params.id},{$set: {email: req.body.email});
But..
overtime this might be an exhaustive task if
I'd suggest to continue with your existing approach as long as
To counter 2nd point, you could disallow unknown fields using Joi validation.
Please try this
student = await Student.updateOne({_id:req.params.id},req.body);