簡體   English   中英

解析 - 在Cloud Code中檢查BeforeSave內的更新

[英]Parse - Check for Update inside BeforeSave in Cloud Code

我想檢查一下,我沒有為事件的參與狀態保存重復條目 - 所以在BeforeSave上我檢查事件rsvp尚未輸入 - 如果有,我想知道是否需要更新。 如果是,我想進行更新而不是創建新的RSVP條目。

這是我的代碼 - 即使使用BeforeSave中的簡單更新,我似乎也無法使其工作。

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

var eventid = request.object.get("eventid");
var userid = request.object.get("userid");
var rsvp_status = request.object.get("rsvp_status");

var Rsvps = Parse.Object.extend("Rsvps");
var query = new Parse.Query(Rsvps);
query.equalTo("eventid", eventid);
query.equalTo("userid", userid);
query.first({
  success: function(object) {
    if (object) {
        // response.error("An RSVP for this event already exists.");
        request.object.id = object.id;
        request.object.set('rsvp_status', "attending");
        request.object.save();
    } else {
      response.success();
    }
  },
  error: function(error) {
    response.error("Error: " + error.code + " " + error.message);
  }
});

});

我已經嘗試了很多變化而沒有任何喜悅 - 這是我最近的嘗試。

@CityLogic你不應該在@ ahoffer的例子中調用第二次保存,因為你在beforeSave觸發器中。 只需設置resp_status並調用response.success()即可。

更新。 我添加了一個檢查,如果“參加”值正確,則不要更新現有對象。 試一試。 如果有任何無法解決的問題,請將錯誤添加為此答案的注釋。

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

    var eventid = request.object.get("eventid");
    var userid = request.object.get("userid");
    var rsvp_status = request.object.get("rsvp_status");

    //Do not re-declare the class
    //var Rsvps = Parse.Object.extend("Rsvps");
    var query = new Parse.Query("Rsvps");

    //Check for existing RSVP
    query.equalTo("eventid", eventid);
    query.equalTo("userid", userid);

    query.first().then(function (object) {

            if (object && object.get('rsvp_status') != "attending") {
                //RSVP exists and needs updating.
                // Do not save the object attached to the request.
                //Instead, update existing object.

                object.set('rsvp_status', "attending");
                object.save().then(function () {
                        response.error('Updated existing RSVP to "attending"');
                    },

                    function (error) {

                        response.error("Error: " + error.code + " " + error.message);
                    });

            } else {

                //Continuing and save the new RSVP object because it is not a duplicate.
                response.success();
            }
        },
        function (error) {

            response.error("Error: " + error.code + " " + error.message);

        });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM