使用Parse,如何设置列唯一或至少检查它是否存在?

时间:2013-10-03 06:40:45

标签: database facebook unique parse-platform

我有一个'单词'表,我想要做的是,如果用户使用该单词,则将其插入表中。但是,如果它已经存在,请更新该单词的计数。

我没有看到将列实际设置为唯一的方法。 那就是说,我如何避免竞争条件:

t1 - user1检查是否使用了“Love”。没有 t2 - user2检查是否使用了“Love”。没有 t3 - user1添加'Love' t4 - user2添加'Love'

我不希望它在数据库中两次。无论如何要在Parse中完成这个任务?

2 个答案:

答案 0 :(得分:1)

您可以使用'exists' query检查具有密钥集的对象:

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);
  }
});

关于防止竞争条件,您可以使用Parse Cloud Code处理此问题。您可以使用Cloud Function来处理数据输入,它应该按顺序处理请求。

答案 1 :(得分:1)

为了避免竞争条件,您应该使列/字段唯一。在与Parse一起使用的数据库中执行此操作(如果您将mongoDB与您的解析服务器一起使用,那么这里是mongoDB的链接,例如 - https://docs.mongodb.com/manual/core/index-unique/)。然后在CloudCode中 - 尝试创建一个新的单词对象并存储它。如果单词已经存在,则商店将失败,然后您可以使用查询来查找现有单词并增加。