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
3 Answers
Reset to default 5You 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
版权声明:本文标题:javascript - Parse body.req inside a loop in Nodejs - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742284962a2446767.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论