0

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).

RobertJoseph
  • 7,968
  • 12
  • 68
  • 113

2 Answers2

1

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();
  }
});
chasew
  • 8,438
  • 7
  • 41
  • 48
1

Parse provides you with an incrementKey method that helps you avoiding problems when multiple users trying to update a counter. You could also decrement or increment by a given amount if needed. They call it Counters. But this only solves the race condition problem.

[myString incrementKey:@"count"];
[myString saveInBackground];

You can find more information here: https://www.parse.com/docs/ios_guide#objects-updating/iOS.

dadederk
  • 315
  • 2
  • 11
  • Please re-read the question. incrementKey: doesn't prevent multiple objects with the same name from being saved. @ccswaden's answer solves this problem entirely. – RobertJoseph Sep 08 '14 at 11:19
  • 1
    You're right, this only solves the race condition problem... I'll take a look on ccwasden's answer. – dadederk Sep 08 '14 at 13:53