我正在尝试创建一个预处理程序,在将所有数据写入 MongoDB 之前对其进行清理 见:http://mongoosejs.com/docs/middleware.html
我已经尝试了以下方法来让每个属性都能够对其进行 sanitizer :
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
请知道如何获取每个属性以便我对其进行 sanitizer ?
~马克
[编辑] 这是一种可能的解决方法,无论如何直接在 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);
最佳答案
您可以使用 mongoose-sanitizer插件,它使用 Google Caja 执行清理。
关于node.js - 在保存到 Mongoose 之前清理数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18318798/