Lokesh Cherukuri
Lokesh Cherukuri

Reputation: 23

Ember.js error: You must include an 'id' for an object passed to 'push'

The REST API which I am using to fetch data doesn't give proper JSON as expected by Ember.js. We don't have id values in our data.

[{"objectID":"340907","owner":"Lokesh"},{"objectID":"340908","owner":"Cherukuri"}]

So, I created a a serializer:

serializers/baddata.js

import DS from 'ember-data';

export default DS.JSONSerializer.extend({
    primaryKey: 'objectID'
});

adapters/baddata.js

import DS from 'ember-data';

export default DS.RESTAdapter.extend({
    host: 'http://localhost:8080',
    buildURL : function(modelName, id) {
        return this.host + "/baddata/trains/"+ id;
    }
});

models/baddata.js

import DS from 'ember-data';

export default DS.Model.extend({
    owner: DS.attr('string')
});

This did not solve the problem. Can someone correct my mistakes?

Upvotes: 1

Views: 2597

Answers (2)

Patrick Fisher
Patrick Fisher

Reputation: 8055

You'll want to use DS.RESTSerializer and override normalizeResponse to turn your data into:

{ baddata: { "id":"340907", "owner":"Lokesh" } }

Converting objectID into id will just make your life easier. You might as well, since you already need to override normalizeResponse to format the payload.

This assumes you are fetching a single record at a time. If you fetch multiple records, you'll want

{
  baddatas: [
    { "id":"340907", "owner":"Lokesh" },
    { "id":"340908","owner":"Cherukuri" }
  ]
}

See DS.RESTSerializer#normalizeResponse

Upvotes: 0

Mirza Memic
Mirza Memic

Reputation: 872

I am using mongo and in your example I see that you have used ApplicationSerializer. I think that you need to use following

If you use JSONSerializer then

import DS from 'ember-data';
export default DS.JSONSerializer.extend({
  primaryKey: 'objectID'
});

If you use REST Serializer

import DS from 'ember-data';
export default DS. RESTSerializer.extend({
  primaryKey: 'objectID'
});

I tried to search ApplicationSerializer class but it is not mentioned under doc. This is what works for me and mongo which I use to change to _id

Hope it helps

Upvotes: 1

Related Questions