node.js - Sanitizing data before saving to Mongoose -
i trying create pre handler sanitizes data before written mongodb see: http://mongoosejs.com/docs/middleware.html
i've tried following each property able sanitize it:
blogschema.pre('save', function (next) { var obj = this; console.log(obj)//-> https://gist.github.com/daslicht/70e0501acd6c345df8c2 // i've tried following single items : object.keys(obj).foreach(function (key) { console.log('keys: ',obj[key]); }); //and: for(var key in obj) { console.log(obj[key]) } //and: _.each( self , function(value, key, list){ console.log('value:',key); }) next(); })
any of above approaches results following:
thats output of:
for(var key in obj) { console.log(obj[key]) }
https://gist.github.com/daslicht/cb855f53d86062570a96
any know how each single property can sanitize it, please?
~marc
[edit] here 1 possible workaround, anyways cleaner have directly on scheme level since more dry
var post = { createdat : req.body.date, createdby : req.user.username, headline : req.body.headline, content : req.body.content } _.each( post , function(value, key, list){ post[key] = sanitize(value).xss(); //its sanetize function of node validator }) var item = new blog(post);
probably not best way it.
mongoose has field validators
the default validators enough job done, custom validators easy create specified in docs.
an example of custom validator docs
var toy = mongoose.model('toy', toyschema); toy.schema.path('color').validate(function (value) { return /blue|green|white|red|orange|periwinkle/i.test(value); }, 'invalid color');
Comments
Post a Comment