我有一个“word”表,我想要做的是,如果用户使用这个单词,就将它插入到表中。但是,如果它已经存在,更新该单词的计数。
我看不出有什么方法可以将列设置为唯一的..。话虽如此,我怎样才能避免比赛条件:
t1 - user1检查是否使用“爱”。不使用t2 - user2检查是否使用“爱”。没有t3 - user1添加了“爱”t4 - user2添加了“爱”
我不希望这两次出现在数据库中。在帕斯完成这件事?
发布于 2013-10-03 07:10:34
您可以使用“存在”查询来检查具有键集的对象:
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);
}
});关于防止比赛条件,您可以使用解析云代码来处理这个问题。您可以有一个云函数来处理数据的输入,并且它应该按顺序处理请求。
发布于 2018-03-20 20:55:54
若要避免争用条件,应使列/字段具有唯一性。在与Parse一起使用的数据库中这样做(如果您在解析服务器上使用mongoDB,那么下面是mongoDB的链接,例如- https://docs.mongodb.com/manual/core/index-unique/)。然后在CloudCode中-尝试创建一个新单词对象并存储它。如果单词已经存在,则存储将失败,然后可以使用查询来查找现有单词和增量。
https://stackoverflow.com/questions/19152434
复制相似问题