Working with Parallel Queries in Meteor

I am dealing with a problem where a user can update a document within a certain time frame, and if not, the server will.

Updating involves incrementing the value and adding an object to the document array. I need to make sure that only one of the users / servers is updating the document. Not both.

To make this happen, some checks are done to check if the document has already been updated, but there are times when the user and the server are running at the same time and both pass checks, and then the document is updated twice.

I tried many different ways to fix this, but I couldn't. I tried to implement a lock like this one: http://en.wikipedia.org/wiki/Peterson%27s_algorithm to ensure that only one update happens and the second update fails, but I don't know if it was successful. Any ideas?

+1


source to share


1 answer


To make this happen, some checks are done to check if the document has already been updated, but there are times when the user and the server are running at the same time and both pass checks, and then the document is updated twice.

You can achieve this by using a MongoDB update query that simultaneously checks if the value has been updated and updates it. Like this:



var post = Posts.findOne("ID");
// ... do some stuff with the post ...
Posts.update({counter: post.counter}, {$push: {items: newItem}, $inc: {counter: 1}});

      

As you can see, in one request, we check the counter and increment it - so if two of these queries are fired one after the other, only one will actually update the document (since the counter will no longer match).

+1


source







All Articles