【问题标题】:Mongoose query middleware/pre-find hooks, what does 'this' refer to?Mongoose 查询中间件/预查找钩子,“this”指的是什么?
【发布时间】:2021-01-11 07:49:50
【问题描述】:

我一直在学习 mongoose 查询中间件,当在查询中间件函数中使用 this 时,它指的是查询对象。

但是,我很难想象查询对象实际上是什么以及如何使用它。例如,如果我有代码:

let query = Model.findById(req.params.id);

如果我当时使用查询中间件:

tourSchema.pre(/^find/, function (next) {
  console.log(this)
  next();
});

this 会是什么?

【问题讨论】:

    标签: node.js express mongoose


    【解决方案1】:

    正如docs中解释的那样

    在查询中间件函数中,this 指的是查询。

    另外,如果你做一个console.log(this),你可以检查对象是这样的:

    Query {
      //a lot of stuffs
    }
    

    也就是说,this 是查询。

    另外,作为另一个例子,您可以使用update 进行以下查询:

    model.update({},{$set:{field:"value"}})
    

    并检查这个钩子:

    MongooseModel.pre('update', async function () {
      const query = this.getUpdate();
      console.log(query) // { '$set': { field: 'value' } }
      const field = query.$set.field;
      console.log(field) // value
    });
    

    【讨论】:

      猜你喜欢
      • 2023-02-18
      • 2021-05-03
      • 1970-01-01
      • 1970-01-01
      • 2021-03-03
      • 2011-01-20
      • 2021-11-26
      • 2018-05-18
      • 1970-01-01
      相关资源
      最近更新 更多