Models

To take advantage of the ORM, Mirage needs to know about your application's models and their relationships. This section will teach you how to define and work with your models, and the next will discuss relationships.

As a clarifying point, Mirage model instances only exist within Mirage's server, and are never shared directly with your app or rendered directly in components. They exist solely to help you manage the data and relationships in your fake backend, but are serialized as a JSON string before they are sent over to your app.

Defining models

To define a model, import the Model class from miragejs and use it as a key on the models config option:

import { Server, Model } from "miragejs"

new Server({
  models: {
    blogPost: Model,
  },
})

The above config defines a BlogPost model within Mirage.

Creating models

To create models, access the model's collection via the schema object. You can access the schema as the first argument in your route handlers:

this.post("/blog-posts", function(schema) {
  let attrs = this.normalizedRequestAttrs()

  schema.blogPosts.create(attrs)
})

You can also access it as server.schema directly off of your Mirage server instance, for example in your default scenario:

new Server({
  models: {
    blogPost: Model,
  },

  seeds(server) {
    server.schema.blogPosts.create({ title: "Interstellar" })
  },
})

Note that the collection is the pluralized form of the model's model name (the blogPost model definition creates a schema.blogPosts collection).

Outside of route handlers, you'll typically create models using Factories via server.create rather than via the schema directly:

seeds(server) {
  server.create("blog-post")
}

Calls to server.create delegate to the schema collection's create method under the hood. We'll talk more about creating data using Factories later in these guides.

Accessing models

To access your models, use the various query methods from the model's collection.

For example, use all() to return all known models:

this.get("/blog-posts", (schema, request) => {
  return schema.blogPosts.all()
})

Here are some other common query methods:

schema.blogPosts.find(1)
schema.blogPosts.first()
schema.blogPosts.where({ isPublished: true })
schema.blogPosts.findBy({ title: "Introduction" })

Check out the Schema API docs to see all available query methods.

Updating and deleting models

Once you're working with an instance of a model, there are other properties and methods you'll have access to.

For example, you can update a model:

let post = schema.blogPosts.find(1)

post.update({ author: "Obi-Wan" })

or delete one:

let post = schema.blogPosts.find(2)

post.destroy()

View the Model API docs to see all the available fields and methods for model instances.


Once your Models have been defined, the next step is to define the relationships between them, so you can really start to leverage the power of Mirage's ORM.

We'll talk about how to do that next.