Parse Cloud Code 中的调用更新

Call update in Parse Cloud 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);
    }
  });
});

如你所见,我调用它之前保存。如果查询未找到任何内容,则创建新条目。如果查询找到某些东西,它应该取这个结果,并且 popularityCount。但事实并非如此。它仅在我之后调用 response.success() 时有效,但调用此函数也会导致创建新条目。

在每次保存时增加对象的计数器似乎是错误的。如果由于其他原因修改了对象怎么办?如果您真的想在每次保存时增加一个字段,则不需要查询——被保存的对象被传递给函数。此外,在保存新对象的情况下,查询将不起作用

如何将查找或创建对象作为一个操作,在应用程序逻辑需要它时增加计数器

 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();
    });
}

现在不需要 beforeSave 逻辑(这似乎是正确的做法,而不是解决方法)。

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