node.js - MongoDB: Update user data based on varying JSON POST data -
using mean environment (including mongoose database access) send varying json data web form (user profile input form) server. there, want update user's document based on data sent server. problem: user related information optional end broad variety of json objects sent server, e.g.
1) {(name: 'fooman', email: 'foo@man.com')} 2) {(name: 'fooman', email: 'foo@man.com', adress:'fooadress')} 3) {(name: 'fooman', email: 'foo@man.com', hasdog:'true')} 4) {(name: 'fooman', email: 'foo@man.com', location: 'footown')}
on server side, end checking every possible json structure update user's document using appropriate mongoose instruction like:
user.update({ _id: userid}, {name: json.name, email: json.email}) ->for case 1 user.update({ _id: userid}, {name: json.name, email: json.email, hasdog: true}) ->for case 3
as can see, leads me ugly , redundant code. hoping architecture advice of how avoid this.
you can build update
object programmatically pulling valid (whitelisted) fields request:
var request = {name: 'fooman', email: 'foo@man.com', hasdog: true, password: 'hack'}; var whitelist = ['name', 'email', 'address', 'hasdog', 'location']; var update = {}; // add whitelisted fields in request update object. (var ix in whitelist) { var field = whitelist[ix]; if (request.hasownproperty(field)) { update[field] = request[field]; } } user.update({ _id: userid }, update);
Comments
Post a Comment