Not long ago I asked in this “topic”: Understanding locking/transactions in mongo - #3 by kevinadi what the best solution is for reading data from a document, running complex logic in my REST server and updating my document based on the previous read. The solution was using transactions. However now I run into a problem where there is no way to lock a document by reading it. This is needed in my case because if not my document can get corrupted.
A solution is that instead of reading I update the document with a random value and this way any other request trying to update the document will get a WriteConflict error. To me, this seems a bit “hacky” as in that it is not hard to implement but that I need to change my data model by adding a random value so other requests get a WriteConflict error. I would like to know if this is the “right” way or if there are other solutions to this problem. I found this solution on a mongo blog: How To SELECT ... FOR UPDATE inside MongoDB Transactions | MongoDB Blog