The data browser is built for Chrome, Firefox, Safari, and IE9 and above. Please upgrade your browser, or download Google Chrome to get the best experience.
Back to Questions

Adding objects to relation. Error: You can't add an unsaved Parse.Object to a relation.

0 votes     1 answer     2.1k views     

0

I tried to establish relation and add objects to relation but it generates an error. My code is here.

// Declare the types.
var Post = Parse.Object.extend("Post");
var Comment = Parse.Object.extend("Comment");

// Create the post
var myPost = new Post();
myPost.set("title", "I'm Hungry");
myPost.set("content", "Where should we go for lunch?");
myPost.save();

var myComment = new Comment();
myComment.set("Content", "Jag tror kebabhus är bra!");
myComment.save();

//var user = Parse.User.current();
var relation = myPost.relation("PostId");
relation.add(myComment);
myPost.save();

Please tell me what's wrong here. Thanks

Error: You can't add an unsaved Parse.Object to a relation. I am not understanding this error. please help me.

- Rana over 1 year ago

1 Answer

3

Objects need to be saved before they can be added to a relation. Since JavaScript is asynchronous, the save() operation on myComment has not finished by the time you added it to the relation.

Try using a callback for the save op on myComment, which would allow you to wait until the save operation has finished:

myComment.save(null, {
  success: function(myComment) {
    // The object was saved successfully.
    var relation = myPost.relation("PostId");
    relation.add(myComment);
    myPost.save();
  },
  error: function(myComment, error) {
    // The save failed.
    // error is a Parse.Error with an error code and description.
  }
});

Hector thank you very much. Now it worked :)

- Rana over 1 year ago