Invalid document version number found in post update middleware

I have a Mongoose plugin that I use to increase the version number of documents ( __v ), as well as create the revision itself. The plugin covers the middleware function Documents Doc.save() , as well as the middleware functions Query update and findOneAndUpdate .

 module.exports = ( schema, options ) => { _.forEach( [ 'save','update', 'findOneAndUpdate' ], query => { // Since the Doc.save() middleware is the only document update middleware function, just isolate that one if( query === 'save' ) schema.pre( query, function( next ) { this.increment() next() } ) // The rest are query updates else schema.pre( query, function() { this.update( {}, { $inc: { __v: 1 } } ) }) // Create revisions for each document update schema.post( query, docData => { Mongoose.models.Revision.createRevision( { docsId: this._id, revision: docData.__v, // <-- This is the wrong number. It one less than it should be document: { /* Stuff.. */ } // More stuff }, ( err, revision ) => { // CB Stuff }) }) }) } 

Thus, it basically works as expected. The value __v document is increased for the interaction of documents and requests, and with audit documents. The part I'm stuck with is related to the functions of the middleware Query, update and findOneAndUpdate . Although __v updated in the document through the pre event, the value of this.__v in the post event does not seem to see the updated value. Thus, this means that the revision is created and refers to the wrong version number of the document.

This is just super weird, because __v really do update when I look at it in the database, but when I console.log this.__v in post update .. it sees the version number before updating.

For a temporary fix, I just increment it manually if its MW query function:

 schema.post( query, docData => { Mongoose.models.Revision.createRevision( { docsId: this._id, revision: ( query === 'save' // Temporary fix.. ? docData.__v : docData.__v+1 ) // Add +1 if its a query function document: { /* Stuff.. */ } // More stuff }, ( err, revision ) => { // CB Stuff }) }) 

But obviously this is just a gang, so if this is a real solution to this, that would be great

Any idea?

0
source share
1 answer

Even though __v updated in the document using the pre event, the value of this.__v in the post event is not like the updated value.

This is most likely because your middleware for update and findOneAndUpdate does not use the async callback to wait for the action to complete before continuing (something that you implemented for the save middleware).

So use the callback:

 schema.pre( query, function(next) { this.update( {}, { $inc: { __v : 1 } }, next); }) 
+1
source

All Articles