最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to update document on pre or post query hook in mongoose? - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question edited Jul 15, 2015 at 5:42 ZeMoon 20.3k5 gold badges60 silver badges99 bronze badges asked Jul 15, 2015 at 0:01 s.alems.alem 13.1k9 gold badges46 silver badges74 bronze badges 2
  • What have you tried? doc.update({$inc: {queryCount: 1}}, callback) doesn't work? – Jason Cust Commented Jul 15, 2015 at 2:35
  • @JasonCust That's what the OP is asking, whether the same can be done on at the model level. This query will have to be run on the controller. – ZeMoon Commented Jul 15, 2015 at 5:42
Add a ment  | 

2 Answers 2

Reset to default 6

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) {

})
发布评论

评论列表(0)

  1. 暂无评论