首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Parse设置列唯一,或者至少先检查列是否存在?

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

Stack Overflow用户
提问于 2013-10-03 06:40:45
回答 2查看 7.3K关注 0票数 1

我有一个“word”表,我想要做的是,如果用户使用这个单词,就将它插入到表中。但是,如果它已经存在,更新该单词的计数。

我看不出有什么方法可以将列设置为唯一的..。话虽如此,我怎样才能避免比赛条件:

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

我不希望这两次出现在数据库中。在帕斯完成这件事?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-10-03 07:10:34

您可以使用“存在”查询来检查具有键集的对象:

代码语言:javascript
复制
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);
  }
});

关于防止比赛条件,您可以使用解析云代码来处理这个问题。您可以有一个云函数来处理数据的输入,并且它应该按顺序处理请求。

票数 1
EN

Stack Overflow用户

发布于 2018-03-20 20:55:54

若要避免争用条件,应使列/字段具有唯一性。在与Parse一起使用的数据库中这样做(如果您在解析服务器上使用mongoDB,那么下面是mongoDB的链接,例如- https://docs.mongodb.com/manual/core/index-unique/)。然后在CloudCode中-尝试创建一个新单词对象并存储它。如果单词已经存在,则存储将失败,然后可以使用查询来查找现有单词和增量。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19152434

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档