[英]parse.com Storing a specific value once
I'm new to the Parse api and am trying to figure out how to do the following: 我是Parse api的新手,正在尝试弄清楚如何执行以下操作:
My app stores strings ("foo", "bar", etc). 我的应用程序存储字符串(“ foo”,“ bar”等)。 "foo" should only exist once no matter how many times users attempt to add it - along with a count of how many times that string was attempted to be added.
无论用户尝试添加多少次,“ foo”仅应存在一次-以及尝试添加该字符串的次数。 Thus if four users attempt to add the string "foo" I'd like the associated
PFObject
to look like: 因此,如果四个用户尝试添加字符串“ foo”,我希望关联的
PFObject
看起来像:
name: "foo"
count: 4
(there should never be more than one object with a name of "foo") (永远不能有多个名称为“ foo”的对象)
I know what I could query for "foo", retrieve it, and then update the count but I have a feeling that a race condition would exist if multiple users are trying to update "foo" at the same time. 我知道我可以查询“ foo”,检索它然后更新计数,但是我有一个感觉,如果多个用户试图同时更新“ foo”,则将存在竞争条件。
What is the right/best way to achieve this via the Parse API (I'm using iOS if it matters). 通过Parse API实现此目的的正确/最佳方法是什么(如果重要,我正在使用iOS)。
Parse cloud code beforeSave
. 解析云代码
beforeSave
。 https://parse.com/docs/cloud_code_guide#functions-modifysave https://parse.com/docs/cloud_code_guide#functions-modifysave
Before a save occurs, check for the existence of the row, and update it, then return response.error()
在进行保存之前,检查该行是否存在,并进行更新,然后返回
response.error()
Something like this: 像这样:
Parse.Cloud.beforeSave("MyObject", function(request, response) {
var newObject = request.object;
if(!newObject.existed()) {
var query = new Parse.Query("MyObject");
var name = newObject.get("name");
query.equalTo("name", name);
query.first().then(function(existing){
if(existing){
existing.increment("count");
return existing.save().then(function(){
response.error(name + " already exists");
});
}
else {
response.success();
}
});
}
else {
response.success();
}
});
Parse provides you with an incrementKey method that helps you avoiding problems when multiple users trying to update a counter. 解析为您提供了一个增量密钥方法,可以帮助您避免多个用户尝试更新计数器时出现问题。 You could also decrement or increment by a given amount if needed.
如果需要,您也可以减少或增加给定的数量。 They call it Counters.
他们称之为柜台。 But this only solves the race condition problem.
但这只能解决种族条件问题。
[myString incrementKey:@"count"];
[myString saveInBackground];
You can find more information here: https://www.parse.com/docs/ios_guide#objects-updating/iOS . 您可以在这里找到更多信息: https : //www.parse.com/docs/ios_guide#objects-updating/iOS 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.