Reputation: 689
I'm completely new to node.js and mongodb and i have a question regarding the synchronisation of multiple requests which occur in the same timeperiod. I already read some threads regarding this topic but i have not found an satisfying answer yet...
I have the following scenario:
The Documents in my Collection have a state property. On a request i select a Document based on the state and update the state afterwards.
The problem is now if there are multiple requests at the same time all requests would select the same Document because the first update is not yet written to the db but each request should get an "own Document" to work with.
Is it evan a good idea to use node.js and mongodb for this requirements or should i stick with "the classic" approaches of RDBMS?
My main focus is on scalability thats the reason why i chose node.js and mongodb in the first place.
I'm very thankfull for every advice you could give me, Best Regards
Upvotes: 1
Views: 346
Reputation: 11671
You can model this concurrent access pattern totally in the client (singleton controller, etc.) or using some MongoDB capabilities. To model it in the database, consider a document structure like the following (examples done in mongo shell):
{ "_id" : 1, "type" : "bathroom", "occupied" : false }
When thread 65 needs to use the bathroom, it issues a findAndModify
query and marks the bathroom it is returned as occupied:
> var thread65_wc = db.restrooms.findAndModify(
{ "query" : { "type" : "bathroom", "occupied" : false },
"update" : { "$set" : { "occupied" : true } } })
findAndModify
is atomic. It will retrieve the document and set occupied : true
without any possibility for another thread to try to use the same bathroom or modify it once thread65 starts to look at it (assuming checks for occupied
by the other threads). Now thread 65 can use the bathroom and, once done with it, vacate it and potentially change other properties:
> db.restrooms.update({ "_id" : thread65_wc._id },
{ "$set" : { "occupied" : false, "dirty" : "very" } } )
Using findAndModify
and an occupied
flag you can ensure each thread gets one document to work with and that that document is not touched by another thread during the original thread's time using it.
Upvotes: 1