Izaac Brånn
Izaac Brånn

Reputation: 94

Modifying Parse.User object before FIRST save

I'm working on an app and I need some changes to be made on new users registering during certain periods.

I've added a variable which I will change manually, and a check if that value is true or false.

This is my current code:

Parse.Cloud.beforeSave(Parse.User, function(request, status)
{
  console.log("********************************************");
  Parse.Cloud.useMasterKey();
  var special = true;
  if(special)
  {
    request.object.set("points", 1000);
    request.object.set("role/objectid", "PZHTquGti0");
  }else{
    request.object.set("points", 0);
    request.object.set("role/objectid", "TQyjIY59oL");
  }
  console.log("********************************************");
  status.success("Job finished successfully!");
}); // end of Parse.define

This code errors out with "Uncaught Error: change must be passed a Parse.Object" and I've been looking through the documentation to find out how to change a value of a subclass of the User object, but have found none.

Also, this code will also run when updating a user, which I don't want it to do. Any help is highly appreciated!

Upvotes: 0

Views: 1013

Answers (1)

satyadeepk
satyadeepk

Reputation: 351

First of all for running the code on first save (insert), you can use request.object.isNew()

As the role column is a pointer, you should set an object & not the id string directly. So create a new dummy object and assign the id to it.

Parse.Cloud.beforeSave(Parse.User, function(request, status)
{
  console.log("********************************************");
  Parse.Cloud.useMasterKey();

  if(request.object.isNew()){ // Object Insert
      var Role = Parse.Object.extend("_Role");
      var role = new Role();

      var special = true;
      if(special)
      {
        request.object.set("points", 1000);
        role.id = "PZHTquGti0";
        request.object.set("role", role);
      }else{
        request.object.set("points", 0);
        role.id = "TQyjIY59oL";
        request.object.set("role", role);
      }
  }
  else{ // Object Update
    //Do nothing
  }
  console.log("********************************************");

  status.success("Job finished successfully!");
}); // end of Parse.define

Upvotes: 1

Related Questions