Models wrap your database, and allow you to define relationships.

Class vs. instance methods

The methods documented below apply to instances of models, but you'll typically use the Schema to access the model class, which can be used to find or create instances.

You can find the Class methods documented under the Schema API docs.

Accessing properties and relationships

You can access properites (fields) and relationships directly off of models.;    // 'Sam';    // Team model
user.teamId;  // Team id (foreign key)

Mirage Models are schemaless in their attributes, but their relationship schema is known.

For example,

let user = schema.users.create();
user.attrs  // { }   // undefined

let user = schema.users.create({ name: 'Sam' });
user.attrs  // { name: 'Sam' }   // 'Sam'

However, if a user has a posts relationships defined,

let user = schema.users.create();
user.posts  // returns an empty Posts Collection


attrs: any

Returns the attributes of your model.

let post = schema.blogPosts.find(1);
post.attrs; // {id: 1, title: 'Lorem Ipsum', publishedAt: '2012-01-01 10:00:00'}

Note that you can also access individual attributes directly off a model, e.g. post.title.


destroy(): any

Destroys the db record.

let post = blogPosts.find(1);
post.destroy(); // removed from the db

isNew(): Boolean

Boolean, true if the model has not been persisted yet to the db.

let post ={title: 'Lorem ipsum'});
post.isNew(); // true;      // null;  // true
post.isNew(); // false;      // 1

isSaved(): Boolean

Boolean, opposite of isNew

reload(): any

Reload a model's data from the database.

let post = blogPosts.find(1);
post.attrs;     // {id: 1, title: 'Lorem ipsum'}

post.title = 'Hipster ipsum';
post.title;     // 'Hipster ipsum';

post.reload();  // true
post.title;     // 'Lorem ipsum'

save(): any

Create or saves the model.

let post ={ title: 'Lorem ipsum' });; // null;; // 1

post.title = 'Hipster ipsum'; // db has not been updated;                  // the db is updated

toString(): String

Simple string representation of the model and id.

let post = blogPosts.find(1);
post.toString(); // "model:blogPost:1"

update(key: String, val: String): any

Updates the record in the db.

let post = blogPosts.find(1);
post.update('title', 'Hipster ipsum'); // the db was updated
  title: 'Lorem ipsum',
  created_at: 'before it was cool'