Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sanitizing data before saving to Mongoose

I am trying to create a pre handler which sanitizes all data before its written to MongoDB see: http://mongoosejs.com/docs/middleware.html

I've tried the following to get each property to be able to sanitize it:

  blogSchema.pre('save', function (next) {
        var obj = this;
        console.log(obj)//-> https://gist.github.com/daslicht/70e0501acd6c345df8c2

        // I've tried the following to get the 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 the above approaches results into something like the following:

Thats the output of:

    for(var key in obj) {
       console.log(obj[key])
    }

https://gist.github.com/daslicht/cb855f53d86062570a96

Any know how to get each single property so that I can sanitize it, please?

~Marc

[EDIT] Here is one possible workaround, anyways it would be cleaner to have it directly on Scheme level since this would be 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 the sanetize function of node validator
        })

        var item = new Blog(post);
like image 475
daslicht Avatar asked Aug 19 '13 16:08

daslicht


1 Answers

You can use mongoose-sanitizer plugin, which uses Google Caja to perform the sanitization.

like image 182
user435943 Avatar answered Jun 20 '23 02:06

user435943