简体   繁体   中英

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.

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

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

Alternatively, you could use a mongoose static method which internally calls 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) {

})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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