I'm new to the Parse api and am trying to figure out how to do the following:
My app stores strings ("foo", "bar", etc). "foo" should only exist once no matter how many times users attempt to add it - along with a count of how many times that string was attempted to be added. Thus if four users attempt to add the string "foo" I'd like the associated PFObject
to look like:
name: "foo"
count: 4
(there should never be more than one object with a name of "foo")
I know what I could query for "foo", retrieve it, and then update the count but I have a feeling that a race condition would exist if multiple users are trying to update "foo" at the same time.
What is the right/best way to achieve this via the Parse API (I'm using iOS if it matters).
Parse cloud code beforeSave
. https://parse.com/docs/cloud_code_guide#functions-modifysave
Before a save occurs, check for the existence of the row, and update it, then return response.error()
Something like this:
Parse.Cloud.beforeSave("MyObject", function(request, response) {
var newObject = request.object;
if(!newObject.existed()) {
var query = new Parse.Query("MyObject");
var name = newObject.get("name");
query.equalTo("name", name);
query.first().then(function(existing){
if(existing){
existing.increment("count");
return existing.save().then(function(){
response.error(name + " already exists");
});
}
else {
response.success();
}
});
}
else {
response.success();
}
});