【问题标题】:Updating existing Parse object in Cloud Code更新 Cloud Code 中的现有 Parse 对象
【发布时间】:2014-04-09 16:39:17
【问题描述】:

我正在使用 Parse 作为我的后端,并希望搜索现有的好友请求并更新这些请求,而不是创建新请求(如果已经存在的话)。

我以为我知道该怎么做,但是当我提交新朋友请求时,即使我找到了现有请求,它们也会被创建为新对象而不是更新旧对象。

这是我正在使用的代码:

Parse.Cloud.beforeSave("FriendRequest", function(request, response) {

    //search for an existing friend request with the same "from" and "to" 
    var query = new Parse.Query("FriendRequest");
        query.equalTo("from", request.object.get("from"))
        .equalTo("to", request.object.get("to"));

    query.find({
      success: function(results) {
        if(results.length > 0)
        {
         var result = results[0];

         //the new request id is undefined as expected
         console.log("request id: " + request.object.id);

         //the result id is valid for an object in the db as expected
         console.log("result id: " + results[0].id);

         //set the id of the request to the id of the existing db object
         request.object.id = results[0].id;

         //the valid id is now in the request object id
         console.log("request id: " + request.object.id);

             //after response.success, the database shows a new entry
             //with a different id
         //instead of updating the existing entry
         response.success();
         }
         }
    });

});

这里没有很多事情发生。查询确实返回成功,并在数据库中输入了正确的条目。我可以确认我获得了数据库中现有项目的正确 objectId。任何想法或想法表示赞赏!

【问题讨论】:

    标签: parse-platform


    【解决方案1】:

    您不能手动设置对象的objectId

    如果您希望beforeSave 不创建新对象(这是您在调用beforeSave 时要做的),您需要手动更新现有对象,然后以失败响应。如果回复response.success(),对象会正常保存。

    在您的代码中,您似乎没有对现有对象进行任何更改。您真正需要做的就是返回response.error (https://parse.com/docs/cloud_code_guide#functions-onsave)

    当然,您还应该以某种方式在代码中处理此问题。通过提醒用户或静默处理。

    但是;如果一个新的好友请求已经存在,为什么你的代码会尝试保存一个新的好友请求?您的应用应该知道存在一个并禁用好友请求按钮或任何 UI 提供的按钮。

    【讨论】:

    • 嗨!感谢您的评论。好吧,我从 Parse 论坛中得到了设置 objectId 的想法,在一篇已有一年多的帖子中,但它来自他们的一位员工,所以我认为它会起作用。我发布的代码已经删除了很多东西,因为我试图弄清楚它为什么不起作用,所以我想消除不必要的东西。我真正想做的是更新请求的状态(例如,接受或拒绝)。所以发出来的请求实际上和我查询的不同。
    • 嗯,也许我在手动设置的 objectId 部分上错了。你有那个帖子的链接吗?
    • 哦,看来你是对的。我从这篇文章中得到了这个想法:parse.com/questions/how-can-i-upsert 但是他们试图设置 objectId 的评论不是来自 Parse 员工。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多