filipp.kowalski
filipp.kowalski

Reputation: 5605

Call update in Parse Cloud Code

I know there were similiar questions, but I see no solution in them. I want to create new object if it doesn't exists in database, and update if one exists. Here is my simple code :

  Parse.Cloud.beforeSave("Tag", function(request, response) {
  var query = new Parse.Query("Tag");
  query.equalTo("name", request.object.get("name"));
  query.first({
    success: function(result) {
        if (!result) {
            response.success();
        } else {
            result.increment("popularityCount");
            result.save();
        }
    },
    error: function(error) {
       alert("Error: " + error.code + " " + error.message);
    }
  });
});

As you see, I am calling it beforeSave. If query doesn't find anything, creates new entry. If query finds something, it should take this result, and popularityCount. But it doesn't. It works only if I call response.success() after that, but calling this function causes also in creating new entry.

Upvotes: 0

Views: 418

Answers (1)

danh
danh

Reputation: 62686

It seems wrong to increment a counter on an object on every save. What if the object is modified for some other reason? If you really do want to increment a field on every save, there's no need for a query -- the object being saved is passed to the function. Moreover, a query will not work in the case where a new object is being saved.

How about instead, find or create the object as one operation, increment the counter when app logic calls for it

 function findOrCreateTagNamed(name) {
    var query = new Parse.Query(Tag);
    query.equalTo("name", name);
    return query.first().then(function(tag) {
        // if not found, create one...
        if (!tag) {
            tag = new Tag();
            tag.set("popularityCount", 0);
            tag.set("name", name);
        }
        return (tag.isNew())? tag.save() : Parse.Promise.as(tag);
    });
}

function incrementPopularityOfTagNamed(name) {
    return findOrCreateTagNamed(name).then(function(tag) {
        tag.increment("popularityCount");
        return tag.save();
    });
}

Now there's no need for beforeSave logic (which seems like the right thing to do, not a workaround).

Parse.Cloud.beforeSave("Tag", function(request, response) {
    var tag = request.object;
    tag.increment("popularityCount");
    response.success();
});

Upvotes: 1

Related Questions