I am currently working on implementing a POST method using mongo/mongoose:
Department
.create({
name: req.body.name,
link: req.body.link,
state: req.body.state,
requirements: req.body.requirements,
salary: req.body.salary,
description: req.body.description
})
The requirements
field is structured as an object with multiple items:
requirements: {
age: 21,
citizenship: "yes",
degree: "4-year"
}
Prior to creating the data, I need to ensure that all required fields are provided:
router.post('/create', (req, res) => {
const requiredFields = ["name", "link", "state", "age", "citizenship", "degree" "salary", "description"];
for(let i=0; i < requiredFields.length; i++){
const field = requiredFields[i];
if(!(field in req.body)){
const message = `Missing \`${field}\` field in request body`;
console.error(message);
return res.status(400).send(message);
};
};
Since age
, citizenship
, and degree
are nested within the requirements
object, directly including them in the requiredFields
list causes an error like
Missing age field in request body
. Any suggestions on how to properly validate their presence in req.body?