Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/sharepoint/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 在mongoose pre中间件中,如何访问更新查询?_Node.js_Mongodb_Express_Mongoose_Mongoose Plugins - Fatal编程技术网

Node.js 在mongoose pre中间件中,如何访问更新查询?

Node.js 在mongoose pre中间件中,如何访问更新查询?,node.js,mongodb,express,mongoose,mongoose-plugins,Node.js,Mongodb,Express,Mongoose,Mongoose Plugins,我正在尝试使用新的不稳定版本mongoose>4.0.0来验证更新查询 假设我想使用以下查询更新架构 schema.update({_id:'blah'},{a:'blah'},function(err){ //do your thing }) 假设我有下面的模式 var schema = new Schema({ a:{type:String} }); schema.pre('update',function(next){ var findQuery=this._conditions;

我正在尝试使用新的不稳定版本mongoose>4.0.0来验证更新查询

假设我想使用以下查询更新架构

schema.update({_id:'blah'},{a:'blah'},function(err){
//do your thing
})
假设我有下面的模式

var schema = new Schema({
a:{type:String}
});

schema.pre('update',function(next){
var findQuery=this._conditions;  // gives {_id:'blah'}

// how do i get {a:'blah'}????

next();
});
如何在预中间件中获取{set:{a:'blah'}}的更新查询,以便在执行更新之前进行一些检查

或者,我知道可以在post中间件中访问更新查询

schema.post('update',function(){
var findQuery=this._conditions;  // gives {_id:'blah'}

var updateQuery=this._update; //gives {$set:{a:'blah'}}

next();
});
但是那太晚了,我需要在实际更新数据库之前在预中间件中检查这个

我尝试查看预中间件的“this”对象,但在任何地方都找不到updateQuery对象,并且此。\在预中间件中未定义更新

有办法做到这一点吗?
谢谢

通过这个特殊的例子,我找到了一个解决方法,但是它并不能完全解决我的实际问题。在mongoose版本~4.0.0中,您可以让预中间件指定在更新时通过模型验证

schema.pre('update',function(next){
    this.options.runValidators = true; // make sure any changes adhere to schema
})
基本上,您可以在模式中指定验证器

var schema = new Schema({
    a:{
        type:String,
        validate:[...] //the validation you want to run
    }
});
您可以使用this.isNew check inside validation函数选择跳过正常保存操作的验证

此代码将在更新查询中的任何$set和$unset上运行validate:[…]


但是,由于某些原因,它不适用于像$push或$addToSet这样的数组操作。因此,如果更新数组,它将根本不会运行验证代码!因此它不能解决我面临的实际问题。但是,它可以与为遇到此特定问题的任何人提供的示例一起工作

如果您仍在寻找一种适用于阵列操作的解决方案,它看起来像是在较新版本的mongoose中(至少
4.0.7+
),
这是在预中间件中定义的更新