在保存到Mongoose之前清理数据

我正在尝试创build一个预处理程序,它在写入MongoDB之前清理所有数据,请参阅: http : //mongoosejs.com/docs/middleware.html

我已经尝试了以下来获得每个属性能够消毒:

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

上述任何一种方法的结果如下所示:

那是输出:

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

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

任何知道如何获得每一个单一的财产,以便我可以消毒呢?

〜马克

[编辑]这是一个可能的解决方法,无论如何它会更清洁直接在计划层面,因为这将是更干

  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执行清理。

可能不是最好的办法。

mongoose有字段validation器

默认的validation器通常足以完成工作,但自定义validation器很容易按照文档中的指定进行创build。

来自文档的自定义validation器的示例

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

这是一个简单的方法来做到这一点。 这使用async.js ,但你可以重构它使用通用的JS循环或任何其他控制stream库。 关键是获取文档字段的数组,然后可以遍历这些字段,并使用当前上下文来获取/设置值。 据我所知,这不会强制非string值的string。 我用string,数字,布尔值和objectIds进行了testing,并将它们成功保存为原始数据types。

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

根据这个线程 ,我认为你可以做到

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

即使您可以成功设置,请注意Model.update 不会触发预存储钩子。 检查这个GitHub问题