Mongoose - Version Error: No matching document found for id

VersionError: No matching document found for id

I had an migration and also some direct queries in mongodb shell on a collection and now i have documents with different __v (some of them are 4 and some of them are 5)

Now when i try to update for the first time i got this error, but in the second try it updates it successfully


And is it a good idea to remove all __v s field or update all documents to an specific version
something like this:
db.collectionName.updateMany({}, { __v: 5 })

PLEASE @everyone help, we are on production and this bug makes a very bad effect on our users|

NodeJS version: 14.15.0
Mongoose version: 5.6.2
mongodb version: 3.5.1

Hello –

The version field is introduced by Mongoose, and is intended to protect your application from two threads / processes attempting to modify the same document, and one of them inadvertently overwriting changes by the other, as in this sequence of events:

  1. Application A reads document 1 at {__v: 3}
  2. Application B reads document 1 at {__v: 3}
  3. Application B makes a change to its copy of document 1 and saves; version in the database is incremented to {__v: 4}
  4. Application A makes a different change to its version of document 1 and attempts to save. This change is rejected because the version fields no longer match

How this works is that, behind the scenes, mongoose’s save() method adds the original value of __v to the filter criteria in an update call, so the save() call effectively has the semantics: "Save these changes to the document if and only if the version field still has the value 3".

How you handle this may depend on your application, and what is causing what is, in effect, a race condition between two threads. For example, if you are confident that Application A is only changing a subset of fields and that no other application should be changing those fields, you can use findOneAndUpdate instead, which ignores the __v field. In most cases, you may want to have Application A retry from the beginning and hope there’s no Application C

1 Like

@Kasir_Barati, was @Jeff_Beal’s answer help you solve your issue? If so, as a courtesy to people helping and to all that might have the same issue, please mark his post as the solution.

1 Like

Yes it was and If I understood @Jeff_Beal right he means this is how the mongoose guarantee the consistency in the MonogDB. Am I right? If that is the case I think trying again is a better option.

But I think maybe it was a better idea to use transactions instead of this default behavior.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.