Save a Parse Object Causes Another Object Saved Too

202 views Asked by At

I am quite new with Parse, I am confused on how parse works.

Here I have a PFUser, PFGroupObject, PFUserGroupObject. Where PFUserGroupObject is a "Table" that relate user an group.

PFUserGroupObject and PFGroupObject is my custom PFObject

What confuses me is that, once I save the PFUserGroupObject, the PFGroupObject is also saved to Parse.

I have 2 questions:

  1. Is this behaviour normal? I know that PFUserGroupObject has a variable that stores PFGroupObject. But, I am wondering if this is the expected behaviour of Parse.

        //MARK - Create a New Group
        var group: PFGroupObject = PFGroupObject();
        group.name = "Friends Group";
    
        //MARK - Create a Many to Many Join Table to Relate User and Group
        var userGroup: PFUserGroupObject = PFUserGroupObject();
        userGroup.user = PFUser.currentUser();
        userGroup.group = group;
    
        //THIS LINE CAUSES MY GROUP OBJECT TO BE SAVED TO PARSE AS WELL
        PFObject.save(userGroup);
    
  2. Let's say I called

       PFObject.saveAll([group, userGroup]);
    

Would the group object saved twice into Parse?

I am trying to understand how Parse works. Thank you!!!!!

1

There are 1 answers

1
Jake T. On

When you save a "Parent" object that has one or more "child" objects, it will save the children as well. I have never worked with PFGroupObjects, but I have a pointer to a custom object attached to each of my users. Rather than having to save my custom object, then save my user (or vice versa), saving just my user will also save my custom object.

There are some nuances with this, such as trying to add a pointer to an unsaved object which you have just created to another object, then saving the parent. While you generated an object id when you created the child object, you haven't actually saved it, so it's a dangling pointer.

Hope this helps!

edit - If you want to see exactly what is getting saved when, add a before save trigger to your cloud code for the object you want to see whether or not is being saved multiple times, with a console print line inside. Do some testing, and check your logs to see how many times the beforeSave trigger is getting called, and that's how many times you are attempting to save an object of that type.