How to update a document for a request before or after a request in a mongoose?

I am trying to update a field on a request hook. For instance:

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

I want to increase and update the field queryCountfor each request findor findOne.

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

I tried several things, but so far have not achieved anything. Can I achieve this in the model or do I need to do this in the controller?

+4
source share
2 answers

What you need is a post . init

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

Alternatively, you can use the static mongoose 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) {

})
+2
source

All Articles