保存到猫鼬之前先对数据进行消毒 [英] Sanitizing data before saving to Mongoose

查看:95
本文介绍了保存到猫鼬之前先对数据进行消毒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个预处理器,以在将所有数据写入MongoDB之前对所有数据进行清理 请参阅: http://mongoosejs.com/docs/middleware.html

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:

那是输出:

    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?

〜马克

这是一种可能的解决方法,无论如何,将其直接放在Scheme级别会更干净,因为这样做会更干燥.

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);

推荐答案

您可以使用 mongoose-sanitizer 插件,该插件使用Google Caja进行清理.

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

这篇关于保存到猫鼬之前先对数据进行消毒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆