Search code examples
javascriptparse-platformparse-cloud-code

Not able to save a custom class object in Parse


I am trying to create a Customer class object which has a one to one relation with the User class. But the object doesn't save without giving any error. Here is my code:

 Parse.Cloud.afterSave(Parse.User, function(request) {
 user = request.object;
 role_name = user.get("role_name");
 user_name = user.get("user_name");
 user_id = user.get("objectId");

  if (role_name == "customer"){
    user = request.object;
    console.log(" I am inside if else");

    var Customer = Parse.Object.extend("Customer");
    var cus = new Customer();
    cus.set("name2" , "albert")
    var relation = cus.relation("userId");
    relation.add(user);
    cus.save(); // Customer object should get saved here 

    cus.save(null, {
    success: function(cus) {
        // Execute any logic that should take place after the object is saved.
        console.log("I am working")
        alert('New object created with objectId: ' + cus.objectId);
    },
      error: function(error) {
        // handleParseError(error);
        console.log(error)
        // Execute any logic that should take place if the save fails.
        // error is a Parse.Error with an error code and message.
      }
    });
  }

});

Log when I run this:

  after_save triggered for _User for user qu808uKOgt:
  Input: {"object":{"createdAt":"2015-10-11T18:36:07.661Z","objectId":"qu808uKOgt","phone":"5678956475","role_name":"customer","updatedAt":"2015-10-11T18:36:07.661Z","username":"newuser16"}}
  Result: Success
  I am inside if else
  {"name2":"apple","userId":{"__op":"AddRelation","objects":      [{"__type":"Pointer","className":"_User","objectId":"qu808uKOgt"}]}}

Solution

  • I fixed this bug by creating a new cloud function, which will be called immediately after the user sign's up.

    Parse.Cloud.define('functionName', function(request, response){
      var currentUser = Parse.User.current();
      var role_name =  currentUser.get("role_name");
    
      if (role_name == "customer"){
      // Do something
      }
      else if (role_name == "service_provider"){
      // Do something else 
      }
    )};