访问POST方法数组中的对象

时间:2018-06-25 17:00:59

标签: javascript arrays mongodb mongoose

我正在通过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);
    };
};

由于agecitizenshipdegree是对象项,因此我无法将其字符串放入requiredFields中。错误发生在Missing age field in request body。知道如何检查req.body中是否提供了它们吗?

1 个答案:

答案 0 :(得分:0)

  1. 要访问嵌套对象,可以将所需字段保存为“ requirement.age”而不是“ age”,然后可以使用lodash库中的get函数。这样您的情况就会变成:

`

if (typeof(_.get(req.body, "requirement.age") === 'undefined')) {
  //Missing field    
}

`

  1. 您可以尝试扁平化req.body结构,例如:

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)