I've an issue with Cloud Code.My problem is explained as:
I try to this using this code:
var MyObject = Parse.Object.extend("MyClass");
Parse.Cloud.beforeSave("MyClass", function(request, response) {
if (!request.object.get("myID")) {
response.error('A MyObject must have a unique myID.');
} else {
var query = new Parse.Query(MyClass);
query.equalTo("myID", request.object.get("myID"));
query.first({
success: function(object) {
if (object) {
object.set('address',request.object.get("address"));
object.save().then(function () {
response.error('Updated existing MyObject address');
},function (error) {
response.error("Error: " + error.code + " " + error.message);
});
} else {
response.success();
}
},
error: function(error) {
response.error("Could not validate uniqueness for this MyObject object.");
}
});
}
});
But this doesn't works and in my Parse.com Log says:
Result: Error: 142 Error: 124 Too many recursive calls into Cloud Code
I know can I achieve what I want?
You have a beforeSave
method that is triggered when an object of MyClass
should be stored. If this method detects that the object searched for already exists, it modifies this object and tries to store it. But this triggers again the beforeSave
method, and so on, an infinite loop.
You could do it on the client side: Check, if the object exists. If not, create it, but if so, add an entry to it. But you should be aware that you will have a problem: If more than 1 client executes this code at the same time, they could all find out that the object does not exist yet, and more than 1 object will be created.
I would thus create such an object right from the beginning, and use the atomic operation addUniqueObject:forKey:
to add entries to an array.