Best Way To Handle Mongo/Couch _id as id with Ember Data

So I’m wondering how people have solved this issue where Mongo passes you an _id as the id? Should I look at writing an adapter? How does this work into the routing convention of :foo_id? Why doesn’t ember respect a computed property called id? I have asked this question on stackoverflow, with examples of what I’ve tried. ember.js - Ember, Ember Data and MongoDB's _id - Stack Overflow

1 Like

If it is globally “_id” then all you have to do is extend the serializer and overwrite the primaryKey method:

App.Serializer = DS.(JSON | REST | your custom one )Serializer.create({
  primaryKey: function(type) {
    return "_id";
  },
  ....
});

So do I need to write an entire Serializer? Can I just extend the Adapter/Serializer instead of creating a new one? I tried the following with no luck.

App.Store = DS.Store.extend({
  revision: 11,
  adapter: 'DS.RESTAdapter'
});

App.Serializer = DS.RESTSerializer.create({
  primaryKey: function(type) {
    return "_id";
  }
});

I also tried the following which results in Uncaught TypeError: Object App.Serializer has no method 'rootForType'

App.Store = DS.Store.extend({
  revision: 11,
  adapter: 'App.Adapter'
});

App.Serializer = DS.Serializer.extend({
  primaryKey: function(type){
    return '_id';
  }
});

App.Adapter = DS.RESTAdapter.extend({
  serializer: 'App.Serializer'
});

You should be able to extend just fine, in your second example the DS.Serializer probably is too low level and does not have that method. Actually checking the code it is only in JSON and REST serializers. And that error is not related to the overriding of the primaryKey method, it is puking because the rest adapter expects you to extend/use the REST serializer.

The reason your first example did not work is because ou are not actually telling your adapter to use the customized serializer, try:

App.Store = DS.Store.extend({
  revision: 11,
  adapter: DS.RESTAdapter.extend({ 
       serializer: App.Serializer
    })
});

Gotcha. Yea I just got it to work. Here is the complete working code:

App.Adapter = DS.RESTAdapter.extend({
  serializer: DS.RESTSerializer.extend({
    primaryKey: function (type){
      return '_id';
   }
  })
});

App.Store = DS.Store.extend({
  revision: 11,
  adapter: 'App.Adapter'
});

Hey @chadhietala!

I’m glad you got an answer, but for future reference, these questions are best for Stack Overflow

Hey @trek.glowacki, no problem.

This topic is now invisible. It will no longer be displayed in any topic lists. The only way to access this topic is via direct link.