Models

AJAX Abstraction for a Single Resource

idAttribute

Name of the attribute returned from the API that serves as the primary key for that resource.

Default Implementation

The default implementation looks like this:

idAttribute: 'id',

Usage

Let's say you have an API endpoint located at http://localhost:1337/tweets/1 that returns a tweet resource looks like this:

{
  id: 1,
  text: 'An old tweet'
}

If you fetch that tweet using this code:

import { Model } from 'lore-models';

const Tweet = Model.extend({
  urlRoot: 'http://localhost:1337/tweets'
})

const tweet = new Tweet({
  id: 1
})

tweet.fetch()

Then once the request returns, you'll be able to access the primary key using tweet.id, and it would return 1.

But some API endpoints don't use id as the name of the attribute representing the primary key. For example, APIs that are backed by MongoDB or CouchDB use _id, and that same resource would be returned like this:

{
  _id: 1,
  text: 'An old tweet'
}

With the default idAttribute, if you now tried to access the primary key using tweet.id, it would return undefined, because there was no id attribute.

To fix that, simply change the value of idAttribute to _id, like this:

import { Model } from 'lore-models';

const Tweet = Model.extend({
  idAttribute: '_id',
  urlRoot: 'http://localhost:1337/tweets'
})

const tweet = new Tweet({
  id: 1
})

tweet.fetch()

Now when you look at tweet.id you'll see 1 again, because it pulled the value from _id.