Reputation: 15547
I have a document like:
{
owner: 'alex',
live: 'some guid'
}
Two or more users can update live field simultaneously.
How can I make sure that only the first user wins and others updates fails?
Upvotes: 0
Views: 131
Reputation: 2814
You can get the semantics you want if you store some variable like "times_updated" in the document. Operations on a single document are atomic, so you can check that the field is the value you expect, and then throw an error if it isn't.
It might look something like:
var timesUpdated = 3
r.table('foo').get(rowId).update(function(row) {
return r.branch(row('timesUpdated').eq(timesUpdated),
{
timesUpdated: row('timesUpdated').add(1),
live: 'some special value'
},
r.error('Someone else updated the live field!')
);
}, {returnChanges: true})
So if another query comes in before you for timesUpdated = 3
, your query will blow up. When do you get timesUpdated
? That depends on how your app is designed, and what you're trying to do.
Another thing to note is that adding {returnChanges: true}
is really useful because it allows you to get the new value of timesUpdated
atomically. You can also see what exactly changed in the updated document.
Upvotes: 1