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
2 Answers
Reset to default 6What 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) {
})