jashkenas / backbone

Give your JS App some Backbone with Models, Views, Collections, and Events
http://backbonejs.org
MIT License
28.1k stars 5.39k forks source link

Renaming the ID to _id because of CouchDB #302

Closed binarykitchen closed 13 years ago

binarykitchen commented 13 years ago

Hello again

Because the CouchDB stores the IDs under the name '_id' I have to map every ID in Backbone models to _id and reverse which is annoying and a waste of bandwidth.

Is there a way tho configure the name of the ID attribute for all Backbone models?

juggy commented 13 years ago

Yes, redefine idAttribute to whatever is the name of your id on your models.

binarykitchen commented 13 years ago

idAttribute? I'm sorry, how can I rename the ID attribute of a Backbone model to _id? I checked your annotated source code but I see 'id' is hardcoded and can't be renamed.

I repeat: In CouchDB IDs are stored under _id, in Backbone under id so one of them needs to be redefined (renamed) otherwise direct JSON communication isn't possible.

Thank you for any hints.

juggy commented 13 years ago

Read around line #159 https://github.com/documentcloud/backbone/blob/master/backbone.js#L159

binarykitchen commented 13 years ago

Oh I see. It's in the trunk ... I tried that but sorry, it's still not working to my expectations.

Because when I save a model back to the CouchDB with PUT the ID name 'id' is used in JSON. Should be '_id' ... on server side I have to rename 'id' to '_id' then I can save that.

I assume the synch() method needs to be fixed. There somehow the ID in params.data should be named like idAttribute.

juggy commented 13 years ago

You can always change it in your toJSON function on the model.

binarykitchen commented 13 years ago

Yes I could but I think this sould be implemented in Backbone. Respect idAttribute in the toJSON function.

cthorne66 commented 11 years ago

For those that may stumble across this. I have created a gist that provides a way to accommodate this by overriding the toJSON method for models & collections. I was also hoping something like this would be supported natively, but I'm sure there are reasons it isn't. https://gist.github.com/cthorne66/5645162. This issue will also apply to MongoDB too, which is how I ran into this

costa commented 9 years ago

I've just stumbled upon this and I agree with @cthorne66 and @binarykitchen — this should be fixed in the core, and #toJSON should be overridden the other way around — if needed (which shouldn't be really). As of this moment, idAttribute is a half-assed surprising functionality. I would open this for discussion if in doubt — this shouldn't break things for sane people, and the rest should adjust.

costa commented 9 years ago

Two weeks passed and my comment above doesn't seem relevant anymore. Huzzah!