Search code examples
javascriptparse-platformparse-cloud-code

Parse Server Cloud Code Save Object


I am attempting to query an object add 1 to the returned integer and then save this object back to my mLabs database using parse server cloud code.

I can successfully query and add 1 to the object that I would like, however I cannot figure out how to successfully save this back to the database. I have tried many solutions all leading to a Parse Server "request timeout"

Parse.Cloud.define("addRating", function(request, response) {

  var currentRatingQuery = new Parse.Query("StudentNotes");
  currentRatingQuery.equalTo("objectId", "Y4bBzvsHb1");
  currentRatingQuery.select("noteRating");
  currentRatingQuery.find({
    useMasterKey: true,
    success: function(results) {
      //var noteRating = results.get("noteRating");
      //noteRating += 1;
      results = Number(results);
      results += 1;
      console.log("NOTE RATINGGGGG: " + results);
      console.log("TYPE OFFFFFFF: " + typeof results);


      results.set('institution', "TEST INSTITUTION");
      results.save(null, {
        useMasterKey: true
      });
      console.log("SAVE SUCCESS", results);
      response.success("rating updated successfully.", results);

    },
    error: function(error) {
      response.error("failed to add 1 to parse cloud code rating. Error: " + error); //THIS GETS CALLED
    }
  });

});

The code above successfully queries the database, but does not save the value back. It results in a Parse Server "request timeout".


Solution

  • My problem was syntax related there is a severe lack of syntax for parse server cloud code due to it being so similar to parse.com cloud code. The following is the working code to retrieve an object and save the object back.

    Parse.Cloud.define('addNoteRating', function(request, response) {
      var SaveObject = Parse.Object.extend("StudentNotes");
      var saveObject = new Parse.Query(SaveObject);
      saveObject.equalTo("objectId", request.params.objectId);
      saveObject.first({
        useMasterKey: true,
        success: function(Objects) {
          Objects.save(null, {
            useMasterKey: true,
            success: function(object) {
              object.increment("noteRating");
              object.save();
              console.log("Cloud Code: User note rating has increased by 1.", object);
              response.success('Cloud Code: User note rating has increased by 1.');
    
            }
          });
        }
      });
    
    });