Adding object to PFRelation through Cloud Code

96 Views Asked by At

I am trying to add an object to a PFRelation in Cloud Code. I'm not too comfortable with JS but after a few hours, I've thrown in the towel.

                    var relation = user.relation("habits");
                    relation.add(newHabit);

                    user.save().then(function(success) {
                        response.success("success!");
                    });

I made sure that user and habit are valid objects so that isn't the issue. Also, since I am editing a PFUser, I am using the masterkey:

    Parse.Cloud.useMasterKey();
1

There are 1 best solutions below

0
On

Don't throw in the towel yet. The likely cause is hinted at by the variable name newHabit. If it's really new, that's the problem. Objects being saved to relations have to have once been saved themselves. They cannot be new.

So...

var user = // got the user somehow
var newHabit = // create the new habit
// save it, and use promises to keep the code organized
newHabit.save().then(function() {
    // newHabit is no longer new, so maybe that wasn't a great variable name
    var relation = user.relation("habits");
    relation.add(newHabit);

    return user.save();
}).then(function(success) {
    response.success(success);
}, function(error) {
    // you would have had a good hint if this line was here
    response.error(error);
});