我正在通过mongo / mongoose创建POST方法:
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
})
需求是包含其他项目的对象:
requirements: {
age: 21,
citizenship: "yes",
degree: "4-year"
}
在创建之前,我正在检查是否提供了所有字段:
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);
};
};
由于age
,citizenship
和degree
是对象项,因此我无法将其字符串放入requiredFields中。错误发生在Missing age field in request body
。知道如何检查req.body中是否提供了它们吗?
答案 0 :(得分:0)
`
if (typeof(_.get(req.body, "requirement.age") === 'undefined')) {
//Missing field
}
`
Object.assign(req.body, req.body.requirement)
// This would make your req.body look like
{
name: 'x',
link: 'y',
requirement: {
age: 1
..
},
age: 1
..
}
或者您可以将其分配给另一个变量,然后使用。
let reqBodyReplica = Object.assign({}, req.body, req.body,requirement)