【问题标题】:In mongoose pre middleware, how do i access the update query?在猫鼬预中间件中,我如何访问更新查询?
【发布时间】:2015-08-05 05:14:40
【问题描述】:

我正在尝试使用新的不稳定版本的 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();
});

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

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

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

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

next();
});

但为时已晚,在实际更新数据库之前,我需要在预中间件中进行检查。

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

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

【问题讨论】:

    标签: node.js mongodb express mongoose mongoose-plugins


    【解决方案1】:

    如果您仍在寻找适用于数组操作的解决方案,它看起来像在较新版本的 mongoose(至少 4.0.7+)中,this._update 是在前置中间件中定义的。

    【讨论】:

      【解决方案2】:

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

      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 检查来选择跳过正常保存操作的验证。

      此代码将在更新查询中对任何 $set 和 $unset 运行 validate:[...]。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-31
        • 1970-01-01
        • 2015-10-21
        • 2012-05-18
        • 2014-01-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多