parse-platformparse-cloud-codeafter-save

request.object.id not returning in afterSave() in Cloud Code


Parse.Cloud.afterSave(function(request) {

var type = request.object.get("type");

  switch (type) {
    case 'inspiration':
      var query = new Parse.Query("Inspiration");
      break;
    case 'event':
      var query = new Parse.Query("Event");
      break;
    case 'idea':
      var query = new Parse.Query("Idea");
      break;
    case 'comment':
      break;
    default:
      return;
  }

  if (query) {
    query.equalTo("shares", request.object.id);
    query.first({
      success: function(result) {
        result.increment("sharesCount");
        result.save();
      },
      error: function(error) {
        throw "Could not save share count: " + error.message;
      }
    });
  }
 });

For some reason request.object.id is not returning the object id from the newly created record. I've tested this code out throughly and have isolated it down to the request.object.id variable. I've even successfully ran it with using a pre-existing object ID and it worked fine. Am I using the wrong variable for the object ID?

Thanks in advanced for any help!


Solution

  • Thanks for the reply. I found out another work around for this for version 1.6.5. I should probably also mention that my use case for this code is to increment a count column (comments count) when a new relation has been added to a particular record (post).

    Instead of implementing an afterSave method on my relation class (comment), I instead implemented a beforeSave method on my class (Post) and used request.object.dirtyKeys() to get my modified columns. From there I check to see if my dirty key was comments and if it is I increment my count column. It works pretty well actually.