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 => {
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 ) => {
But obviously this is just a gang, so if this is a real solution to this, that would be great
Any idea?