Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create lock on a Mongoose object

I have two callbacks that are often modifying the same mongo object with mongoose. The modification is complex such that I can't easily do it in one update(). As a result, a lot of the times only one of the two updates is applied, and I get a [VersionError: No matching document found.] error.

Is there any way to explicitly lock the document so that each update can wait for the other to finish, and can happen without worrying about a race condition?

like image 573
maxko87 Avatar asked Feb 10 '15 19:02

maxko87


1 Answers

Mongodb does not support object locking, you could however implement it yourself.

You have to choices

  • Optimistic concurrency control (when there is low contention for the resource) - This can be easily implemented using versionNumber or timeStamp field. On read you retrieve versionNo/timeStamp and supply it to all updates where it is checked and if matches incremented.

  • Pessimistic concurrency control (when single document is updated frequently) - this is bit more problematic technique since you have to cover recovering from the various failure scenarios when your operations do not complete successfully. (i.e. process dies)

if you decide to follow 2nd option here is interesting read it covers situations when you update number objects in "single" operation though

like image 168
marcinn Avatar answered Nov 11 '22 15:11

marcinn