Home > Back-end >  Prevent update of mongodb document having previous older __v version
Prevent update of mongodb document having previous older __v version

Time:11-08

I have active versioning in mongodb. In every update __v get incremented. if A and B has made two request and got document verson 2. If A updates the document and the version becomes 3. I have to prevent B from making the update without refreshing Because A and B could have conflict.

CodePudding user response:

Add __v to the query conditions.

If, for example, your current query predicate is:

{
  key: "abc"
}

It can be modified to include the current value of the __v field, e.g.:

{
  key: "abc",
  __v: 2
}

Playground example here.

In your described scenario when clients A and B have both made the request at the same time, then the following will happen:

  1. Each request will identify the same candidate document and optimistically attempt to perform the change.
  2. One of the two operations will be determined to have been "first" and it will modify the docuemnt.
  3. The second operation will encounter a write conflict. It will automatically retry, but it will no longer match the document as the __v field had been incremented by the other update.
  • Related