I am new to both MongoDB and Backbone, and I find it challenging to grasp the concepts. My main issue revolves around manipulating attributes in Backbone.Model to efficiently use only the necessary data in Views. Specifically, I have a model:
window.User = Backbone.Model.extend({
urlRoot:"/user",
idAttribute: "_id",
defaults: {
_id: null,
name: "",
email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="54323b3b143635267a361e">[email protected]</a>"
}
});
window.UserCollection = Backbone.Collection.extend({
model: User,
url: "user/:id"
});
Additionally, I have a View:
beforeSave: function(){
var self = this;
var check = this.model.validateAll();
if (check.isValid === false) {
utils.displayValidationErrors(check.messages);
return false;
}
this.saveUser();
return false;
},
saveUser: function(){
var self = this;
console.log('before save');
this.model.save(null, {
success: function(model){
self.render();
app.navigate('user/' + model.id, false);
utils.showAlert('Success!', 'User saved successfully', 'alert-success');
},
error: function(){
utils.showAlert('Error', 'An error occurred while trying to save this item', 'alert-error');
}
});
}
I need to utilize the 'put' method with data from any fields except '_id'. For instance, the desired format should be:
{"name": "Foo", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="97f1f8f8d7f5f6e5b9f5f6ed">[email protected]</a>"}
However, regardless of my actions, each request always contains:
{**"_id": "5083e4a7f4c0c4e270000001"**, "name": "Foo", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="abcdc4c4ebc9cad985c9cad1">[email protected]</a>"}
This leads to an error from the server:
MongoError: cannot change _id of a document old:{ _id: ObjectId('5083e4a7f4c0c4e270000001'), name: "Foo" } new:{ _id: "5083e4a7f4c0c4e270000001", name: "Bar", email: "[email protected]" }
Github link: https://github.com/pruntoff/habo
Thank you in advance!