admin管理员组

文章数量:1334132

How can i parse and save body of POST request with mongoose in Nodejs using a for loop, in order to avoid to save every property manually?

I would like to do something like

for(var param in body)
  Model.param=req.body.param;

instead of

Model.name=req.body.name;
Model.email=req.body.email;
Model.birth=req.body.birth;
...

considering also that some body parameters are array.

How can i parse and save body of POST request with mongoose in Nodejs using a for loop, in order to avoid to save every property manually?

I would like to do something like

for(var param in body)
  Model.param=req.body.param;

instead of

Model.name=req.body.name;
Model.email=req.body.email;
Model.birth=req.body.birth;
...

considering also that some body parameters are array.

Share Improve this question asked Jun 15, 2017 at 9:14 user8025570user8025570 1
  • @VedranMaricevic not sure I see how destructuring would be any different than the solution the OP is looking to avoid? – James Commented Jun 15, 2017 at 9:42
Add a ment  | 

3 Answers 3

Reset to default 5

You don't need a loop at all

Object.assign(Model, req.body)

Code like this should work, even for the arrays.

for(var property in req.body) {
    Model[property] = req.body[property];
}

Try something like this:

for (let key of Object.keys(req.body)) {
  Model[key] = req.body[key]
}

Object.keys() is a safer way of getting all the keys instead of in. As in operator matches all object keys, including those in the object's prototype chain.

本文标签: javascriptParse bodyreq inside a loop in NodejsStack Overflow