Easy way to upgrade Mongoose document versions for any update requests?

I want to start using the version of the Mongooses document (__v key). I had a problem actually increasing the version value, and I found that when executing the request, I need to add this.increment() .

Is there a way to auto zoom? For now, I just added it to the pre middleware for update type queries:

 module.exports = Mongoose => { const Schema = Mongoose.Schema const modelSchema = new Schema( { name: Schema.Types.String, description: Schema.Types.String } ) // Any middleware that needs to be fired off for any/all update-type queries _.forEach( [ 'save', 'update', 'findOneAndUpdate' ], query => { // Increment the Mongoose (__v)ersion for any updates modelSchema.pre( query, function( next ) { this.increment() next() } ) } ) } 

This seems to work. But I kind of thought that there would already be a way to do this inside Mongoose .. am I mistaken?

+6
source share
1 answer

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 .

+4
source

All Articles