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

你离开我真会死。 提交于 2019-12-13 04:47:42

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/19152434/using-parse-how-do-i-set-a-column-unique-or-at-least-check-if-it-exists-first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!