Mongoose - Version Error: No matching document found for id

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

6 Likes