Class DS.Store

The store contains all of the data for records loaded from the server. It is also responsible for creating instances of DS.Model that wrap the individual data for a record, so that they can be bound to in your Handlebars templates.

Define your application's store like this:

app/stores/application.js
1
2
3
4
import DS from 'ember-data';

export default DS.Store.extend({
});

Most Ember.js applications will only have a single DS.Store that is automatically created by their Ember.Application.

You can retrieve models from the store in several ways. To retrieve a record for a specific id, use DS.Store's find() method:

1
2
store.find('person', 123).then(function (person) {
});

By default, the store will talk to your backend using a standard REST mechanism. You can customize how the store talks to your backend by specifying a custom adapter:

app/adapters/application.js
1
2
3
4
import DS from 'ember-data';

export default DS.Adapter.extend({
});

You can learn more about writing a custom adapter by reading the DS.Adapter documentation.

Store createRecord() vs. push() vs. pushPayload()

The store provides multiple ways to create new record objects. They have some subtle differences in their use which are detailed below:

createRecord is used for creating new records on the client side. This will return a new record in the created.uncommitted state. In order to persist this record to the backend you will need to call record.save().

push is used to notify Ember Data's store of new or updated records that exist in the backend. This will return a record in the loaded.saved state. The primary use-case for store#push is to notify Ember Data about record updates (full or partial) that happen outside of the normal adapter methods (for example SSE or Web Sockets).

pushPayload is a convenience wrapper for store#push that will deserialize payloads if the Serializer implements a pushPayload method.

Note: When creating a new record using any of the above methods Ember Data will update DS.RecordArrays such as those returned by store#peekAll(), store#findAll() or store#filter(). This means any data bindings or computed properties that depend on the RecordArray will automatically be synced to include the new or updated record values.

Show:

Module: ember-data
modelName
String
returns
DS.RecordArray

This method returns a filtered array that contains all of the known records for a given type in the store.

Note that because it's just a filter, the result will contain any locally created records of the type, however, it will not make a request to the backend to retrieve additional records. If you would like to request all the records from the backend please use store.find.

Also note that multiple calls to all for a given type will always return the same RecordArray.

Example

1
var localPosts = store.all('post');
Module: ember-data
modelName
String
inputProperties
Object
a hash of properties to set on the newly created record.
returns
DS.Model
record

Create a new record in the current store. The properties passed to this method are set on the newly created record.

To create a new instance of a Post:

1
2
3
store.createRecord('post', {
  title: "Rails is omakase"
});

To create a new instance of a Post that has a relationship with a User record:

1
2
3
4
5
var user = this.store.peekRecord('user', 1);
store.createRecord('post', {
  title: "Rails is omakase",
  user: user
});
Module: ember-data
record
DS.Model

For symmetry, a record can be deleted via the store.

Example

1
2
3
4
5
var post = store.createRecord('post', {
  title: "Rails is omakase"
});

store.deleteRecord(post);
Module: ember-data
modelName
String
query
Object
optional query
filter
Function
returns
DS.PromiseArray

Takes a type and filter function, and returns a live RecordArray that remains up to date as new records are loaded into the store or created locally.

The filter function takes a materialized record, and returns true if the record should be included in the filter and false if it should not.

Example

1
2
3
store.filter('post', function(post) {
  return post.get('unread');
});

The filter function is called once on all records for the type when it is created, and then once on each newly loaded or created record.

If any of a record's properties change, or if it changes state, the filter function will be invoked again to determine whether it should still be in the array.

Optionally you can pass a query, which is the equivalent of calling find with that same query, to fetch additional records from the server. The results returned by the server could then appear in the filter if they match the filter function.

The query itself is not used to filter records, it's only sent to your server for you to be able to do server-side filtering. The filter function will be applied on the returned results regardless.

Example

1
2
3
4
5
6
7
8
store.filter('post', { unread: true }, function(post) {
  return post.get('unread');
}).then(function(unreadPosts) {
  unreadPosts.get('length'); // 5
  var unreadPost = unreadPosts.objectAt(0);
  unreadPost.set('unread', false);
  unreadPosts.get('length'); // 4
});
Module: ember-data
modelName
String
id
(Object|String|Integer|null)
options
Object
returns
Promise
promise

This is the main entry point into finding records. The first parameter to this method is the model's name as a string.


To find a record by ID, pass the id as the second parameter:

1
store.find('person', 1);

The find method will always return a promise that will be resolved with the record. If the record was already in the store, the promise will be resolved immediately. Otherwise, the store will ask the adapter's find method to find the necessary data.

The find method will always resolve its promise with the same object for a given type and id.


You can optionally preload specific attributes and relationships that you know of by passing them as the third argument to find.

For example, if your Ember route looks like /posts/1/comments/2 and your API route for the comment also looks like /posts/1/comments/2 if you want to fetch the comment without fetching the post you can pass in the post to the find call:

1
store.find('comment', 2, { preload: { post: 1 } });

If you have access to the post model you can also pass the model itself:

1
2
3
store.find('post', 1).then(function (myPostModel) {
  store.find('comment', 2, {post: myPostModel});
});

This way, your adapter's find or buildURL method will be able to look up the relationship on the record and construct the nested URL without having to first fetch the post.


To find all records for a type, call findAll:

1
store.findAll('person');

This will ask the adapter's findAll method to find the records for the given type, and return a promise that will be resolved once the server returns the values. The promise will resolve into all records of this type present in the store, even if the server only returns a subset of them.

Module: ember-data
modelName
String
options
Object
returns
DS.AdapterPopulatedRecordArray

findAll ask the adapter's findAll method to find the records for the given type, and return a promise that will be resolved once the server returns the values. The promise will resolve into all records of this type present in the store, even if the server only returns a subset of them.

app/routes/authors.js
1
2
3
4
5
6
7
import Ember from 'ember';

export default Ember.Route.extend({
  model: function(params) {
    return this.store.findAll('author');
  }
});
Module: ember-data
modelName
String
id
(String|Integer)
options
Object
returns
Promise
promise

This method returns a record for a given type and id combination.

The findRecord method will always return a promise that will be resolved with the record. If the record was already in the store, the promise will be resolved immediately. Otherwise, the store will ask the adapter's find method to find the necessary data.

The findRecord method will always resolve its promise with the same object for a given type and id.

Example

app/routes/post.js
1
2
3
4
5
6
7
import Ember from 'ember';

export default Ember.Route.extend({
  model: function(params) {
    return this.store.findRecord('post', params.post_id);
  }
});

If you would like to force the record to reload, instead of loading it from the cache when present you can set reload: true in the options object for findRecord.

app/routes/post/edit.js
1
2
3
4
5
6
7
import Ember from 'ember';

export default Ember.Route.extend({
  model: function(params) {
    return this.store.findRecord('post', params.post_id, { reload: true });
  }
});
Module: ember-data
modelName
String
id
String|Integer
returns
DS.Model|null
record

Get a record by a given type and ID without triggering a fetch.

This method will synchronously return the record if it is available in the store, otherwise it will return null. A record is available if it has been fetched earlier, or pushed manually into the store.

Note: This is an synchronous method and does not return a promise.

1
2
3
var post = store.getById('post', 1);

post.get('id'); // 1
Module: ember-data
modelName
(String|DS.Model)
inputId
(String|Integer)
returns
Boolean

Returns true if a record for a given type and ID is already loaded.

Module: ember-data
modelName
String
returns
DS.Model

Returns a model class for a particular key. Used by methods that take a type key (like find, createRecord, etc.)

Module: ember-data
modelName
String
The name of the model type for this payload
payload
Object
returns
Object
The normalized payload

normalize converts a json payload into the normalized form that push expects.

Example

1
2
3
4
5
socket.on('message', function(message) {
  var modelName = message.model;
  var data = message.data;
  store.push(modelName, store.normalize(modelName, data));
});
Module: ember-data
modelName
String
returns
DS.RecordArray

This method returns a filtered array that contains all of the known records for a given type in the store.

Note that because it's just a filter, the result will contain any locally created records of the type, however, it will not make a request to the backend to retrieve additional records. If you would like to request all the records from the backend please use store.find.

Also note that multiple calls to peekAll for a given type will always return the same RecordArray.

Example

1
var localPosts = store.peekAll('post');
Module: ember-data
modelName
String
id
String|Integer
returns
DS.Model|null
record

Get a record by a given type and ID without triggering a fetch.

This method will synchronously return the record if it is available in the store, otherwise it will return null. A record is available if it has been fetched earlier, or pushed manually into the store.

Note: This is an synchronous method and does not return a promise.

1
2
3
var post = store.peekRecord('post', 1);

post.get('id'); // 1
Module: ember-data
modelName
String
data
Object
returns
DS.Model|Array
the record(s) that was created or updated.

Push some data for a given type into the store.

This method expects normalized data:

  • The ID is a key named id (an ID is mandatory)
  • The names of attributes are the ones you used in your model's DS.attrs.
  • Your relationships must be:
    • represented as IDs or Arrays of IDs
    • represented as model instances
    • represented as URLs, under the links key

For this model:

app/models/person.js
1
2
3
4
5
6
7
8
import DS from 'ember-data';

export default DS.Model.extend({
  firstName: DS.attr(),
  lastName: DS.attr(),

  children: DS.hasMany('person')
});

To represent the children as IDs:

1
2
3
4
5
6
{
  id: 1,
  firstName: "Tom",
  lastName: "Dale",
  children: [1, 2, 3]
}

To represent the children relationship as a URL:

1
2
3
4
5
6
7
8
{
  id: 1,
  firstName: "Tom",
  lastName: "Dale",
  links: {
    children: "/people/1/children"
  }
}

If you're streaming data or implementing an adapter, make sure that you have converted the incoming data into this form. The store's normalize method is a convenience helper for converting a json payload into the form Ember Data expects.

1
store.push('person', store.normalize('person', data));

This method can be used both to push in brand new records, as well as to update existing records.

Module: ember-data
modelName
String
datas
Array
returns
Array

If you have an Array of normalized data to push, you can call pushMany with the Array, and it will call push repeatedly for you.

Module: ember-data
modelName
String
Optionally, a model type used to determine which serializer will be used
inputPayload
Object

Push some raw data into the store.

This method can be used both to push in brand new records, as well as to update existing records. You can push in more than one type of object at once. All objects should be in the format expected by the serializer.

app/serializers/application.js
1
2
3
import DS from 'ember-data';

export default DS.ActiveModelSerializer;
1
2
3
4
5
6
7
8
9
10
var pushData = {
  posts: [
    { id: 1, post_title: "Great post", comment_ids: [2] }
  ],
  comments: [
    { id: 2, comment_body: "Insightful comment" }
  ]
}

store.pushPayload(pushData);

By default, the data will be deserialized using a default serializer (the application serializer if it exists).

Alternatively, pushPayload will accept a model type which will determine which serializer will process the payload. However, the serializer itself (processing this data via normalizePayload) will not know which model it is deserializing.

app/serializers/application.js
1
2
3
import DS from 'ember-data';

export default DS.ActiveModelSerializer;
app/serializers/post.js
1
2
3
import DS from 'ember-data';

export default DS.JSONSerializer;
1
2
store.pushPayload('comment', pushData); // Will use the application serializer
store.pushPayload('post', pushData); // Will use the post serializer
Module: ember-data
modelName
String
query
Any
an opaque query to be used by the adapter
returns
Promise
promise

This method delegates a query to the adapter. This is the one place where adapter-level semantics are exposed to the application.

Exposing queries this way seems preferable to creating an abstract query language for all server-side queries, and then require all adapters to implement them.


If you do something like this:

1
store.query('person', { page: 1 });

The call made to the server, using a Rails backend, will look something like this:

1
2
3
Started GET "/api/v1/person?page=1"
Processing by Api::V1::PersonsController#index as HTML
Parameters: { "page"=>"1" }

If you do something like this:

1
store.query('person', { ids: [1, 2, 3] });

The call to the server, using a Rails backend, will look something like this:

1
2
3
Started GET "/api/v1/person?ids%5B%5D=1&ids%5B%5D=2&ids%5B%5D=3"
Processing by Api::V1::PersonsController#index as HTML
Parameters: { "ids" => ["1", "2", "3"] }

This method returns a promise, which is resolved with a RecordArray once the server returns.

Module: ember-data
type
String or subclass of DS.Model
query
Any
an opaque query to be used by the adapter
returns
Promise
promise

This method delegates a query to the adapter. This is the one place where adapter-level semantics are exposed to the application.

Exposing queries this way seems preferable to creating an abstract query language for all server-side queries, and then require all adapters to implement them.

This method returns a promise, which is resolved with a RecordObject once the server returns.

Module: ember-data
modelName
String
id
String
returns
Boolean

This method returns if a certain record is already loaded in the store. Use this function to know beforehand if a find() will result in a request or that it will be a cache hit.

Example

1
2
3
4
store.recordIsLoaded('post', 1); // false
store.find('post', 1).then(function() {
  store.recordIsLoaded('post', 1); // true
});
Module: ember-data
modelName
String=

This method unloads all records in the store.

Optionally you can pass a type which unload all records for a given type.

1
2
store.unloadAll();
store.unloadAll('post');
Module: ember-data
record
DS.Model

For symmetry, a record can be unloaded via the store. Only non-dirty records can be unloaded.

Example

1
2
3
store.find('post', 1).then(function(post) {
  store.unloadRecord(post);
});