DEV Community

Discussion on: How to Implement Transactions in MongoDB Using Node.js

Collapse
 
stolenche profile image
Stolenche

Great article, good example, thank you. I was wondering, how about the scenario when two users want to book the same listings at the same time since there is a possibility for them to get the same availability result in datesReserved? Does Mongo support more fine-grained locking mechanism to prevent this situation where data can be overwritten?

Collapse
 
alexandrusimandi profile image
Alexandru Simandi

If you are using only one instance of a service to talk with Mongo then you shouldn't worry as this part of Node.js is single threaded. The only thing bad that can happen is a race condition, meaning that even if the first user did the action first before the second user there is a chance that the second user gets processed first.

The feature that you are actually looking for is resource locking. As far as i know, mongodb doesn't support locking natively but you can add a locked: Boolean property on the model and check if it's locked the first thing in the transaction. It should work but I just woke up and wrote this so I might mistaken.

Also ref: docs.mongodb.com/manual/faq/concur...

Collapse
 
lauren_schaefer profile image
Lauren Schaefer • Edited

Whichever call makes it to the database first will succeed. If the second transaction begins while the first is still running, a writeConflict will occur and the transaction will be aborted. If you are using MongoDB 4.2 or greater, the Node.js driver will then retry the transaction. The transaction code checks for the conflict, so the transaction will catch the error and manually abort the transaction.

See mongodb.com/blog/post/how-to-selec... for more details on how locking works in transactions.