Search code examples
databasefacebookuniqueparse-platform

Using Parse, how do I set a column unique or at least check if it exists first?


I have a table of 'words', and what I want to do is, if a user uses that word, insert it into the table. But, if it already exists, update the count on that word.

I don't see a way to actually set columns as unique.. That said, how do I avoid the race condition:

t1 - user1 checks if 'Love' is used. NO t2 - user2 checks if 'Love' is used. NO t3 - user1 adds 'Love' t4 - user2 adds 'Love'

I do not want this to be in the database twice. Anyway to accomplish this in Parse?


Solution

  • You can use the 'exists' query to check for objects which have the key set:

    var Word = Parse.Object.extend("words");
    var query = new Parse.Query(Word);
    query.exists("Love");
    query.find({
      success: function(results) {
        if(results.length === 0){
          // Insert a new word object with the 'Love' key set to 1
          var newWord = new Word();
          newWord.set('Love', 1);
          newWord.save(null, {
            success: function(newWord) {
              alert('New object created with objectId: ' + newWord.id);
            },
            error: function(newWord, error) {
              alert('Failed to create new object, with error code: ' + error.description);
            }
          });
        } else {
          // Get the existing word object and increment its 'Love' key by 1
          var existingWord = results[0];
          var currCount = existingWord.get('Love');
          existingWord.set('Love', currCount + 1);
          existingWord.save(null, {
            success: function(existingWord) {
              alert('Existing object saved with objectId: ' + newWord.id);
            },
            error: function(existingWord, error) {
              alert('Failed to save existing object, with error code: ' + error.description);
            }
          });
        }
      },
      error: function(error) {
        alert("Error: " + error.code + " " + error.message);
      }
    });
    

    With regard to preventing race conditions, you could handle this with Parse Cloud Code. You could have a Cloud Function which handles the input of the data and it should handle the requests sequentially.