在保存到Mongoose之前清理数据

时间:2022-10-13 09:38:31

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

我正在尝试创建一个预处理程序,在写入MongoDB之前清理所有数据,请参阅: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

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

[编辑]这是一个可能的解决方法,无论如何,将它直接放在Scheme级别会更干净,因为这样会更干

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

4 个解决方案

#1


3  

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

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

#2


2  

Probably not the best way to do it.

可能不是最好的方法。

Mongoose has field validators

Mongoose有现场验证员

The default validators are usually enough to get the job done, but custom validators are easy to create as specified in the docs.

默认验证器通常足以完成工作,但自定义验证器很容易按照文档中的规定创建。

An example of a custom validator from the 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');

#3


0  

Here's a simple way to do it. This uses async.js, but you could refactor it to use a generic JS loop or any other control flow library. The key is to get an array of the document's fields, then you can iterate over those and get/set the values using the current context with this. As far as I know, this will not coerce non-string values into strings. I've tested it with strings, numbers, booleans and objectIds and they are successfully saved as their original data types.

这是一个简单的方法。这使用async.js,但您可以重构它以使用通用JS循环或任何其他控制流库。关键是获取文档字段的数组,然后您可以迭代这些字段并使用当前上下文获取/设置值。据我所知,这不会将非字符串值强制转换为字符串。我用字符串,数字,布尔值和objectIds对它进行了测试,并将它们成功保存为原始数据类型。

yourSchema.pre('save', function (next) {
  var self = this;

  // Get the document's fields
  var fields = Object.keys(this._doc);

  // Iteratively sanitize each field
  async.each(fields, function(field, cb) {
    self[field] = validator.escape(self[field]);
    cb();
  }, function(err){
    next();
  });
});

#4


0  

According to This Thread, I think you can do

根据This Thread,我认为你可以做到

blogSchema.pre('save', function (next) {
    var obj = this;
    blogSchema.schema.eachPath(function(path) {
        SanitizeAndThrowErrorIfNecessary(obj(path), next);
    }); 
    //Validation and Sanitization passed
    next();
})

Even if you can set this up successfully, please note that Model.update will not trigger pre save hook. Check This GitHub issue

即使你可以成功设置它,请注意Model.update不会触发预保存挂钩。检查此GitHub问题

#1


3  

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

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

#2


2  

Probably not the best way to do it.

可能不是最好的方法。

Mongoose has field validators

Mongoose有现场验证员

The default validators are usually enough to get the job done, but custom validators are easy to create as specified in the docs.

默认验证器通常足以完成工作,但自定义验证器很容易按照文档中的规定创建。

An example of a custom validator from the 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');

#3


0  

Here's a simple way to do it. This uses async.js, but you could refactor it to use a generic JS loop or any other control flow library. The key is to get an array of the document's fields, then you can iterate over those and get/set the values using the current context with this. As far as I know, this will not coerce non-string values into strings. I've tested it with strings, numbers, booleans and objectIds and they are successfully saved as their original data types.

这是一个简单的方法。这使用async.js,但您可以重构它以使用通用JS循环或任何其他控制流库。关键是获取文档字段的数组,然后您可以迭代这些字段并使用当前上下文获取/设置值。据我所知,这不会将非字符串值强制转换为字符串。我用字符串,数字,布尔值和objectIds对它进行了测试,并将它们成功保存为原始数据类型。

yourSchema.pre('save', function (next) {
  var self = this;

  // Get the document's fields
  var fields = Object.keys(this._doc);

  // Iteratively sanitize each field
  async.each(fields, function(field, cb) {
    self[field] = validator.escape(self[field]);
    cb();
  }, function(err){
    next();
  });
});

#4


0  

According to This Thread, I think you can do

根据This Thread,我认为你可以做到

blogSchema.pre('save', function (next) {
    var obj = this;
    blogSchema.schema.eachPath(function(path) {
        SanitizeAndThrowErrorIfNecessary(obj(path), next);
    }); 
    //Validation and Sanitization passed
    next();
})

Even if you can set this up successfully, please note that Model.update will not trigger pre save hook. Check This GitHub issue

即使你可以成功设置它,请注意Model.update不会触发预保存挂钩。检查此GitHub问题