JP.
JP.

Reputation: 564

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?

Upvotes: 1

Views: 7781

Answers (2)

Evtim Georgiev
Evtim Georgiev

Reputation: 683

To avoid race conditions, you should make the column/field unique. Do that in the database that you use with with Parse (if you use mongoDB with your parse server, then here's a link for mongoDB for example - https://docs.mongodb.com/manual/core/index-unique/). Then in CloudCode - try to create a new word object and store it. If the word already exists, the store will fail and then you can use a query to find the existing word and increment instead.

Upvotes: 5

Daniel Bank
Daniel Bank

Reputation: 3899

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.

Upvotes: 1

Related Questions