Hairgami_Master
Hairgami_Master

Reputation: 5539

How to save an object relationship with Cloud Code and Parse.com?

After saving an object, I'd like to create a private object with a relationship to the first object. I'm curious if I should be using the .afterSave method, or something within the success callback of the first object save.

If I'm supposed to do it in the afterSave method, I'm not sure how to get a reference to the object without access to a debugger- I'm assuming request.object is the just saved object? Needless to say, this code is not working. It is creating and saving both objects, just not the relation between the two.

Any ideas? Many thanks.

Parse.Cloud.beforeSave("Subscription", function(request, response) {
 if (request.object.isNew()){
    request.object.set("url", Math.random().toString(36).substring(7));
    request.object.set("active", true);
    response.success();
 }
 else{
     response.error("Couldn't save Subscription for some reason. Sorry");
 }
});

Parse.Cloud.afterSave("Subscription", function(request,response){
//Add SubscriptionLog object to Subscription

var SubscriptionLog = Parse.Object.extend("SubscriptionLog");
var subscriptionLog = new SubscriptionLog();

subscriptionLog.save(null, {
    success: function(savedSL){
        //create relation of subscriptionLog to subscription
        var relation = request.object.relation("subscriptionLog");
        relation.add(subscriptionLog);
        relation.save();
    },
    error: function(error){
        console.log(error);
    }
  });
})

Upvotes: 0

Views: 2943

Answers (2)

LostInTheTrees
LostInTheTrees

Reputation: 1145

I believe that since you appear to have only one Subscription for each SubscriptionLog, you just need an object pointer in the SubscriptionLog, not a relation. Just assign the objectID to the pointer.

Before the beforeSave executes response.success() there is no objectID for Subscription. So at the least, you need to do this after response.success(). However, I have never checked to see if the objectID is available in beforeSave, but after that call. I do the assignment in an afterSave function.

Upvotes: 1

Héctor Ramos
Héctor Ramos

Reputation: 9258

You should use the afterSave hook for this. The object that was just saved is request.object.

Your afterSave hook is wrongly formatted - there is no "response" object. The correct format is:

Parse.Cloud.afterSave("Subscription", function(request) {
  // ...
});

Upvotes: 0

Related Questions