I am fetching a mongodb collection from server using backbone collection. Since the ids are stored as ‘_id’, I used idAttribute to map it to ‘_id’.
(function(){
var PlaceModel = Backbone.Model.extend({
idAttribute: "_id",
});
var PlaceCollection = Backbone.Collection.extend({
url: "http://localhost:9090/places",
initialize: function(options){
var that = this;
this.fetch({
success: function(){
console.log("Success!", that.toJSON());
},
error: function(){
console.log("Error");
}
});
}
});
var place = new PlaceCollection({model:PlaceModel});
}());
But later on when I try to access the model’s ‘idAttribute’ when it’s time to DELETE an entry, it returns ‘id’ instead of ‘_id’, which means this.model.isNew() from the view returns ‘true’ for all the records fetched from the server. Therefore I cannot DELETE nor PUT an entry to the server.
However if I set the idAttribute using prototype like this (instead of inside the PlaceModel definition):
Backbone.Model.prototype.idAttribute = "_id";
Then it correctly maps the idAttribute to ‘_id’, and everything works. What might be happening?
When you say this:
That’s the same, more or less, as saying this:
You’re not setting the collection “class”‘s
modelproperty, you’re just creating a collection with one model in it (a plainBackbone.Modelinstance, not aPlaceModel) and that model has amodelattribute with valuePlaceModel.So, given all that, the collection has no idea that its model is supposed to have
idAttribute: "_id"or even that its model is supposed to be aPlaceModel. You want to see themodelwhen you createPlaceCollection, not when you createplace: