I am writing a REST API in Golang and I am using MongoDB as the database. Some things about locking data/transactions are unclear to me. In my case, I am storing data in a two-dimensional array. When a user makes a request I am retrieving the corresponding document from the database. In Go I run some complex logic to check if the request is valid, change the two-dimensional array and update the document with the new array.
From my understanding, this could go wrong because if this user would make two rapid requests after each other or another user makes a request after the retrieval of the document the data will be old and invalid in which case the document will not have the new data and data may get corrupted.
What I would like to do is lock the document before I retrieve the document and only release the lock after I have run my logic and updated the document. I have not found out how to do this. I feel that the things I find about transactions are more about multi-document/collection updates and it doesn’t work with a standard database because you will need a cluster/replica-set?. Other answers advise using compounds like FindOneAndUpdate however this would not work in my case because I would need to run logic between “find” and “update”.