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?
On my journey to explore MongoDB and Mongoose's powerful features over the years, I encountered something called pre and post hooks, few years back. They are simple yet powerful tools with which you can manipulate model instances, queries, perform validation before or after an intended database operation etc.
According to the official mongoose documentation here – Middleware (also called pre and post hooks) are functions which are passed control during execution of asynchronous functions. Middleware is specified on the schema level and is useful for writing plugins.
In MongoDB, all documents are unique because of the _id field or path that MongoDB uses to automatically create a new document. For this reason, finding a document is easy with Mongoose. To find a document using its _id field, we use the findById() function.
Working with save() When you create an instance of a Mongoose model using new , calling save() makes Mongoose insert a new document. If you load an existing document from the database and modify it, save() updates the existing document instead.
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) {
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With