Stop 08 · ORMs & Query BuildersTopics · 7/10

Schema Definition

Part of the Backend Developer Roadmap

In short

Every ORM starts with a schema: a description of your tables in code. It becomes the single source of truth for types, validation and migrations.

Declaring your data models — fields, types, relationships, constraints — in your ORM's format, which then generates or validates against your actual database schema.

The blob at a bank desk holds up a stack of identical blank forms.

Think of it like this

The bank's blank form

Before anyone opens an account, the bank designs a form: name, mobile, address, signature, nothing else. Every customer fills the same form, so every record looks alike. A schema in code is that blank form for your database rows.

Watch it happen

What a model describes

model User
id: primary key
email: unique
role: USER|ADMIN
posts: Post[]
Post.authorId

1/5A model maps to one table. Its name, User, usually becomes the table name.

The big ideas

What you need to know

Single source of truth

Types, migrations and validation all come from one schema. Change it once and everything follows.

Types and modifiers

Each field has a type plus modifiers: optional, default value, unique, or a database-specific type.

Relations

Declare how models connect. The ORM works out the foreign keys and join queries.

Enums and defaults

Enums limit a field to a fixed list. Defaults like now() fill fields you don't send.

See it in code

Walk through the code

prisma
1enum Role {2  USER3  ADMIN4}5model User {6  id    Int     @id @default(autoincrement())7  email String  @unique8  name  String?9  role  Role    @default(USER)10  posts Post[]11}12model Post {13  id       Int  @id @default(autoincrement())14  authorId Int15  author   User @relation(fields: [authorId], references: [id])16}

1/4An enum: role can only ever be USER or ADMIN.

This is Prisma's schema language. TypeORM uses decorated classes and Mongoose uses Schema objects, but they describe the same things.

Save yourself the pain

Common mistakes

Oops

Making every field optional to avoid errors.

Do this instead

Optional fields spread null checks all over your code. Make a field required unless it's genuinely missing sometimes.

Oops

Maintaining ORM models and a separate SQL file by hand.

Do this instead

Pick one source of truth, usually the ORM schema, and generate migrations from it.

Your mission

Schema for a canteen app

~20 min

Quick check

In the schema above, what does the ? in name String? mean?

Go deeper

  1. 1Define a schema with at least one one-to-many and one many-to-many relationship.
  2. 2Learn how your ORM's schema syntax maps to underlying SQL `CREATE TABLE` statements.
  3. 3Practice adding a new field to an existing schema and generating the migration.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge