简体   繁体   English

如何在mongoose中更新pre或post查询钩子上的文档?

[英]How to update document on pre or post query hook in mongoose?

I am trying to update a field on a query hook. 我正在尝试更新查询挂钩上的字段。 For example: 例如:

var mySchema = new Schema({
  name: String,
  queryCount: {type: Number, default:0}
});

I want to increment and update queryCount field on each find or findOne query. 我想在每个findfindOne查询上增加和更新queryCount字段。

mySchema.post('find', function (doc) {
  // here is the magic
});

I have tried a few things but no success so far. 到目前为止,我尝试了一些但没有成功的事情。 Can I achieve this in model or do I have to do it in the controller? 我可以在模型中实现这一点,还是必须在控制器中完成?

What you want is a post init hook 你想要的是一个post init钩子

mySchema.post('init', function (doc) {
  doc.queryCount++;
  doc.save();
});

Alternatively, you could use a mongoose static method which internally calls findAndUpdate() 或者,您可以使用findAndUpdate()静态方法,该方法在内部调用findAndUpdate()

mySchema.statics.findWithIncrement = function (query, callback) {

    this.findAndUpdate(query, { $inc: { queryCount: 1 })
        .exec(function(err, res) {

            if (err) return callback(err);

            //Handle response
        });
}

And then use the method in your controllers: 然后在控制器中使用该方法:

MyModel.findWithIncrement({name: "someName"}, function (err, result) {

})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM