简体   繁体   中英

efficient way of moving req.body properties to model object

I'm looking for a shortcut to some of the tedious boilerplate code I've been doing when creating a crud REST api. I'm using express and posting an object which I wish to save.

app.post('/', function(req, res){
  var profile = new Profile();

  //this is the tedious code I want to shortcut

  profile.name = req.body.name;
  profile.age = req.body.age;
  ... and another 20 properties ...

  //end tedious code

  profile.save()
});

Is there an easy way to just apply all req.body properties to the profile object? I will be writing the same crud code for sever different models and the properties will be changing frequently during development.

How about a for-in loop, assuming your new Profile() will generate a good schema to put values on, which will avoid req.body to mess you up.

for (var key in profile) {
  if (profile.hasOwnProperty(key) && req.body.hasOwnProperty(key))
    profile[key] = req.body[key];
}

More precisely, you should have a parse/stringify function for each of your module for this case. So that you can simply call:

var profile = Profile.parse(req.body);

In fact, if you are playing with non-IE browsers or in node.js/rhino, and your req.body is clean , you can just do it like:

var profile = req.body;
profile.__proto__ = Profile.prototype;

And you're done.

Can do something like this:

for(key in req.body) {
  profile[key] = req.body[key];
}

Iterating over all keys is probably a bad idea. Better would be:

['name', 'age', ...].forEach(function(key) {
    profile[key] = req.body[key];
});

The easiest way is to use spread operator (...).

app.post('/', function(req, res){
  var profile = new Profile({...req.body});
  profile.save()
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM