I am writing a web application where more users can perform simultaneous operation in the same document in mongodb. I use the mean.io stack, but I am quite new to it. I was wondering how does mongoose manage concurrency. Every "user click" operation performs first a read to get the document, and a save after some calculations. Of course the sequence read-calculate-save is not atomic. Does mongoose work with 'last change wins' policy, or does it throw a versioning error? Does it make sense in this case to use a queue?
Thanks, best regards.
With Optimistic Concurrency The idea behind optimistic concurrency is to track the version of the document and increment the version every time you save() . If the version of the document in the database changed between when you loaded the document and when you save() , Mongoose will throw an error.
MongoDB allows multiple clients to read and write the same data. To ensure consistency, MongoDB uses locking and concurrency control to prevent clients from modifying the same data simultaneously.
MongoDB uses reader-writer locks that allow concurrent readers shared access to a resource, such as a database or collection, but in MMAPv1, give exclusive access to a single write operation. WiredTiger uses optimistic concurrency control. WiredTiger uses only intent locks at the global, database and collection levels.
In MongoDB, all documents are unique because of the _id field or path that MongoDB uses to automatically create a new document. For this reason, finding a document is easy with Mongoose. To find a document using its _id field, we use the findById() function.
Yes the last change will win.
A queue could be a good option to solve the problem but I'll suggest 2 other ways:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With