Start a new topic

Updating a Model using Backbone

Hey,

i think this is an easy question, but i couldn't figure it out ...



The goal is to just update avalue on an existing model in the datasource structure. Everything i've tried so far results in an unknown error.



So: (Using Backbone/ Titanium Alloy)



Do i have to fetch the specific model per Id and than call the "save" method?( or update method? or could this be done in one smaller "nicer" step? )



In my understanding this:



var SquadUser = Kinvey.Backbone.Model.extend({ url: 'squaduser' });

var model = new SquadUser({

_id: args.squaduser_id

});



should give me the reference to the model and so it's possible to call the update or save after that ?! Like



promise = model.save({

example : 5}, {

success: function(model, response, options) {

console.log("Save: " + response);

},

error : function(error){

Alloy.Globals.parseError(error);

}

});





A short Code snippet would be great.



Best,

Nico








Glad to hear it's working now! As for the error message, I agree, something more helpful is definitely needed. Any chance you can describe the context of the error? Not sure what you mean the "error object was just undefined". Any code or stack trace you can post would be helpful!
Hey I've got it :)



The error (of course) was that the user can't write to the collection, cause it's an entry that comes from another person ...

So - now it's working like expecting.



But:

Shouldn't Kinvey throw an error like "can't write to collection" or something else? My error object just was undefined each time.



Best,

Nico
Nico - not sure what would be causing that behavior ... any chance you could post more of your code, or more context for the error (i.e. a stack trace and/or the exact error message)?
Hey, thanks for the quick answer!





In your example i think it have to be "_id" in the model creation step instead of "id".



But no matter what i am trying ("save" or "update") - i always receive an undefined error.





Best,

Nico

Nico - if you attempting to update an entity already present in Kinvey, you probably want to fetch it first. So, using your example, let's say you have a "squaduser" collection in the Kinvey Data Store, and you want to update the "squaduser" entity whose "_id" is "1234":



var SquadUser = Kinvey.Backbone.Model.extend({ url: 'squaduser' });

var model = new SquadUser({ id: "1234" });

model.fetch({

success: function() {

// now `model` has loaded all the data from Kinvey's server

model.save({ foo: "bar"}, {

success: function() {

// It saved!

},

error: function() {

// something went wrong ...

}

});

}

});



Let me know if that helps, or if you were looking for something else.
Login or Signup to post a comment