Schema

The primary use of the Schema class is to use it to find Models and Collections via the Model class methods.

The Schema is most often accessed via the first parameter to a route handler:

this.get('posts', schema => {
  return schema.posts.where({ isAdmin: false });
});

It is also available from the .schema property of a server instance:

server.schema.users.create({ name: 'Yehuda' });

To work with the Model or Collection returned from one of the methods below, refer to the instance methods in the API docs for the Model and Collection classes.

Fields

db: Object

Returns Mirage's database. See the Db docs for the db's API.

Methods

all(type: any): any

Return all models in the database.

let posts = blogPosts.all();
// [post:1, post:2, ...]

create(type: any, attrs: any): any

Create a new model instance with attributes attrs, and insert it into the database.

let post = blogPosts.create({title: 'Lorem ipsum'});
post.title;   // Lorem ipsum
post.id;      // 1
post.isNew(); // false

find(type: any, ids: any): any

Return one or many models in the database by id.

let post = blogPosts.find(1);
let posts = blogPosts.find([1, 3, 4]);

findBy(type: any, attributeName: any): any

Returns the first model in the database that matches the key-value pairs in attrs. Note that a string comparison is used.

let post = blogPosts.findBy({ published: true });

N.B. This will return null if the schema doesn't have any matching record.

findOrCreateBy(type: any, attributeName: any): any

Returns the first model in the database that matches the key-value pairs in attrs, or creates a record with the attributes if one is not found.

// Find the first published blog post, or create a new one.
let post = blogPosts.findOrCreateBy({ published: true });

first(type: any): any

Returns the first model in the database.

let post = blogPosts.first();

N.B. This will return null if the schema doesn't contain any records.

new(type: any, attrs: any): any

Create a new unsaved model instance with attributes attrs.

let post = blogPosts.new({ title: 'Lorem ipsum' });
post.title;   // Lorem ipsum
post.id;      // null
post.isNew(); // true

none(type: any): any

Return an empty collection of type type.

where(type: any, query: any): any

Return an ORM/Collection, which represents an array of models from the database matching query.

If query is an object, its key-value pairs will be compared against records using string comparison.

query can also be a compare function.

let posts = blogPosts.where({ published: true });
let posts = blogPosts.where(post => post.published === true);