Simple Ember Data setup problems


#1

I’m trying out Ember Data for the first time and I can’t seem to get it to work.

I have an API written in NodeJS (http://localhost:3002) where I can return a collection of states (http://localhost:3002/states).

In my states route I have:

model: function() { 
    return this.store.find('states');
}

http://localhost:3002/states returns json formatted similar to this when tested with Postman:

[
    {
        "_id": "33dc0aecde4be108724cd5fz",
        "name": "California",
        "abbreviation": "CA",
        "cities": [
            {
                "name": "Modesto"
            },
            {
                "name": "Fresno"
            }
        ]
    },
    {
        "_id": "34dc0afcde4be108724cd5fb",
        "name": "Florida",
        "abbreviation": "FL",
        "cities": [
            {
                "name": "Tallahassee"
            },
            {
                "name": "Orlando"
            }
        ]
    }
]

This is what I’m currently seeing in the console in Chrome:

Do I need an adapter, model and serializer? If a model is required…how do I format a model for states that is an array of ‘state’?


#2

The default adapter used in Ember CLI is the RESTAdapter. This adapter will work with the following example output:

{
  "posts": [
    {
      "id": 1,
      "name": "Post 1"
    },
    {
      "id": 2,
      "name": "Post 2"
    }
  ]
}

The problem you’re having with your current JSON is that the objects are anonymous. The fixed output (below) would work at minimum:

{
  "states": [
    {
      "_id": "33dc0aecde4be108724cd5fz",
      "name": "California",
      "abbreviation": "CA",
      "cities": [
        {
          "name": "Modesto"
        },
        {
          "name": "Fresno"
        }
      ]
    },
    {
      "_id": "34dc0afcde4be108724cd5fb",
      "name": "Florida",
      "abbreviation": "FL",
      "cities": [
        {
          "name": "Tallahassee"
        },
        {
          "name": "Orlando"
        }
      ]
    }
  ]
}

Finally, you would need to override the application-serializer unless you rename your _id field to id. Here is how you would do that:

Ember CLI example would be created at app/serializers/application.js

import DS from 'ember-data';

export default DS.RESTSerializer.extend({
  primaryKey: '_id'
});

This alone would allow you to get up and running. Where you will experience further problems is with the embedded records seen in your JSONs cities field. It’s best that your state model uses just an empty DS.attr() value for that particular property.

Hope this helps!


#3

Thanks for the feedback. I’ll make some changes and see how it goes.