I would say that this is the way to go. pre middleware is right for this need, and I don't know another way. This is actually what I do in all of my schemes.
What you need to know is the difference between document and query middleware. The document is executed for init , validate , save and remove operations. There, this refers to a document:
schema.pre('save', function(next) { this.increment(); return next(); });
Queries are executed for the operations count , find , findOne , findOneAndRemove , findOneAndUpdate and update . There, this refers to the request object. Updating the version field for such operations will look like this:
schema.pre('update', function( next ) { this.update({}, { $inc: { __v: 1 } }, next ); });
Source: mongoose documentation .
source share