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.More precisely, you should have a parse/stringify function for each of your module for this case. So that you can simply call:
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:
And you’re done.