# Models (/docs/orm/v6/prisma-schema/data-model/models)

Location: ORM > v6 > Prisma Schema > Data Model > Models

The data model definition part of the [Prisma schema](/orm/v6/prisma-schema/overview) defines your application models (also called **Prisma models**). Models:

* Represent the **entities** of your application domain
* Map to the **tables** (relational databases like PostgreSQL) or **collections** (MongoDB) in your database
* Form the foundation of the **queries** available in the generated [Prisma Client API](/orm/v6/prisma-client/setup-and-configuration/introduction)
* When used with TypeScript, Prisma Client provides generated **type definitions** for your models and any [variations](/orm/v6/prisma-client/type-safety/operating-against-partial-structures-of-model-types) of them to make database access entirely type safe.

The following schema describes a blogging platform - the data model definition is highlighted:

  

#### Relational databases

```prisma highlight=10-46;normal 
datasource db {
  provider = "postgresql"
}

generator client {
  provider = "prisma-client"
  output   = "./generated"
}

model User { // [!code highlight]
  id      Int      @id @default(autoincrement()) // [!code highlight]
  email   String   @unique // [!code highlight]
  name    String? // [!code highlight]
  role    Role     @default(USER) // [!code highlight]
  posts   Post[] // [!code highlight]
  profile Profile? // [!code highlight]
} // [!code highlight]

model Profile { // [!code highlight]
  id     Int    @id @default(autoincrement()) // [!code highlight]
  bio    String // [!code highlight]
  user   User   @relation(fields: [userId], references: [id]) // [!code highlight]
  userId Int    @unique // [!code highlight]
} // [!code highlight]

model Post { // [!code highlight]
  id         Int        @id @default(autoincrement()) // [!code highlight]
  createdAt  DateTime   @default(now()) // [!code highlight]
  updatedAt  DateTime   @updatedAt // [!code highlight]
  title      String // [!code highlight]
  published  Boolean    @default(false) // [!code highlight]
  author     User       @relation(fields: [authorId], references: [id]) // [!code highlight]
  authorId   Int // [!code highlight]
  categories Category[] // [!code highlight]
} // [!code highlight]

model Category { // [!code highlight]
  id    Int    @id @default(autoincrement()) // [!code highlight]
  name  String // [!code highlight]
  posts Post[] // [!code highlight]
} // [!code highlight]

enum Role { // [!code highlight]
  USER // [!code highlight]
  ADMIN // [!code highlight]
} // [!code highlight]
```

#### MongoDB

```prisma highlight=10-45;normal 
datasource db {
  provider = "mongodb"
  url      = env("DATABASE_URL")
}

generator client {
  provider = "prisma-client-js"
}

model User { // [!code highlight]
  id      String   @id @default(auto()) @map("_id") @db.ObjectId // [!code highlight]
  email   String   @unique // [!code highlight]
  name    String? // [!code highlight]
  role    Role     @default(USER) // [!code highlight]
  posts   Post[] // [!code highlight]
  profile Profile? // [!code highlight]
} // [!code highlight]

model Profile { // [!code highlight]
  id     String @id @default(auto()) @map("_id") @db.ObjectId // [!code highlight]
  bio    String // [!code highlight]
  user   User   @relation(fields: [userId], references: [id]) // [!code highlight]
  userId String @unique @db.ObjectId // [!code highlight]
} // [!code highlight]

model Post { // [!code highlight]
  id          String     @id @default(auto()) @map("_id") @db.ObjectId // [!code highlight]
  createdAt   DateTime   @default(now()) // [!code highlight]
  title       String // [!code highlight]
  published   Boolean    @default(false) // [!code highlight]
  author      User       @relation(fields: [authorId], references: [id]) // [!code highlight]
  authorId    String     @db.ObjectId // [!code highlight]
  categoryIDs String[]   @db.ObjectId // [!code highlight]
  categories  Category[] @relation(fields: [categoryIDs], references: [id]) // [!code highlight]
} // [!code highlight]

model Category { // [!code highlight]
  id      String   @id @default(auto()) @map("_id") @db.ObjectId // [!code highlight]
  name    String // [!code highlight]
  postIDs String[] @db.ObjectId // [!code highlight]
  posts   Post[]   @relation(fields: [postIDs], references: [id]) // [!code highlight]
} // [!code highlight]

enum Role { // [!code highlight]
  USER // [!code highlight]
  ADMIN
}
```

The data model definition is made up of:

* [Models](#defining-models) ([`model`](/orm/v6/reference/prisma-schema-reference#model) primitives) that define a number of fields, including [relations between models](#relation-fields)
* [Enums](#defining-enums) ([`enum`](/orm/v6/reference/prisma-schema-reference#enum) primitives) (if your connector supports Enums)
* [Attributes](#defining-attributes) and [functions](#using-functions) that change the behavior of fields and models

The corresponding database looks like this:

<img alt="Sample database" src="/img/orm/sample-database.png" width="1768" height="938" />

<details>
  <summary>
    A model maps to the underlying structures of the data source.
  </summary>

  * In relational databases like PostgreSQL and MySQL, a `model` maps to a **table**
  * In MongoDB, a `model` maps to a **collection**

  > **Note**: In the future there might be connectors for non-relational databases and other data sources. For example, for a REST API it would map to a *resource*.
</details>

The following query uses Prisma Client that's generated from this data model to create:

* A `User` record
* Two nested `Post` records
* Three nested `Category` records

  

#### Query Example

```ts
const user = await prisma.user.create({
  data: {
    email: "ariadne@prisma.io",
    name: "Ariadne",
    posts: {
      create: [
        {
          title: "My first day at Prisma",
          categories: {
            create: {
              name: "Office",
            },
          },
        },
        {
          title: "How to connect to a SQLite database",
          categories: {
            create: [{ name: "Databases" }, { name: "Tutorials" }],
          },
        },
      ],
    },
  },
});
```

#### Copy-Paste Example

```ts
import { PrismaClient } from "../prisma/generated/client";

const prisma = new PrismaClient({});

// A `main` function so that you can use async/await
async function main() {
  // Create user, posts, and categories
  const user = await prisma.user.create({
    data: {
      email: "ariadne@prisma.io",
      name: "Ariadne",
      posts: {
        create: [
          {
            title: "My first day at Prisma",
            categories: {
              create: {
                name: "Office",
              },
            },
          },
          {
            title: "How to connect to a SQLite database",
            categories: {
              create: [{ name: "Databases" }, { name: "Tutorials" }],
            },
          },
        ],
      },
    },
  });

  // Return user, and posts, and categories
  const returnUser = await prisma.user.findUnique({
    where: {
      id: user.id,
    },
    include: {
      posts: {
        include: {
          categories: true,
        },
      },
    },
  });

  console.log(returnUser);
}

main();
```

Your data model reflects *your* application domain. For example:

* In an **ecommerce** application you probably have models like `Customer`, `Order`, `Item` and `Invoice`.
* In a **social media** application you probably have models like `User`, `Post`, `Photo` and `Message`.

Introspection and migration [#introspection-and-migration]

There are two ways to define a data model:

* **Write the data model manually and use Prisma Migrate**: You can write your data model manually and map it to your database using [Prisma Migrate](/orm/v6/prisma-migrate/getting-started). In this case, the data model is the single source of truth for the models of your application.
* **Generate the data model via introspection**: When you have an existing database or prefer migrating your database schema with SQL, you generate the data model by [introspecting](/orm/v6/prisma-schema/introspection) your database. In this case, the database schema is the single source of truth for the models of your application.

Defining models [#defining-models]

Models represent the entities of your application domain. Models are represented by [`model`](/orm/v6/reference/prisma-schema-reference#model) blocks and define a number of [fields](/orm/v6/reference/prisma-schema-reference#model-fields). In the example data model above, `User`, `Profile`, `Post` and `Category` are models.

A blogging platform can be extended with the following models:

```prisma
model Comment {
  // Fields
}

model Tag {
  // Fields
}
```

Mapping model names to tables or collections [#mapping-model-names-to-tables-or-collections]

Prisma model [naming conventions (singular form, PascalCase)](/orm/v6/reference/prisma-schema-reference#naming-conventions) do not always match table names in the database. A common approach for naming tables/collections in databases is to use plural form and [snake\_case](https://en.wikipedia.org/wiki/Snake_case) notation - for example: `comments`. When you introspect a database with a table named `comments`, the result Prisma model will look like this:

```prisma
model comments {
  // Fields
}
```

However, you can still adhere to the naming convention without renaming the underlying `comments` table in the database by using the [`@@map`](/orm/v6/reference/prisma-schema-reference#map-1) attribute:

```prisma
model Comment {
  // Fields

  @@map("comments")
}
```

With this model definition, Prisma ORM automatically maps the `Comment` model to the `comments` table in the underlying database.

> **Note**: You can also [`@map`](/orm/v6/reference/prisma-schema-reference#map) a column name or enum value, and `@@map` an enum name.

`@map` and `@@map` allow you to [tune the shape of your Prisma Client API](/orm/v6/prisma-client/setup-and-configuration/custom-model-and-field-names#using-map-and-map-to-rename-fields-and-models-in-the-prisma-client-api) by decoupling model and field names from table and column names in the underlying database.

[Watch video](https://www.youtube.com/watch?v=oaZkHJiRFWw)

Defining fields [#defining-fields]

The properties of a model are called *fields*, which consist of:

* A **[field name](/orm/v6/reference/prisma-schema-reference#model-fields)**
* A **[field type](/orm/v6/reference/prisma-schema-reference#model-fields)**
* Optional **[type modifiers](#type-modifiers)**
* Optional **[attributes](#defining-attributes)**, including [native database type attributes](#native-types-mapping)

A field's type determines its *structure*, and fits into one of two categories:

* [Scalar types](#scalar-fields) (includes [enums](#defining-enums)) that map to columns (relational databases) or document fields (MongoDB) in the database - for example, [`String`](/orm/v6/reference/prisma-schema-reference#string) or [`Int`](/orm/v6/reference/prisma-schema-reference#int)
* Model types (the field is then called [relation field](/orm/v6/prisma-schema/data-model/relations#relation-fields)) - for example `Post` or `Comment[]`.

The following table describes `User` model's fields from the sample schema:

<details>
  <summary>
    Expand to see table
  </summary>

  | Name      | Type      | Scalar vs Relation            | Type modifier | Attributes                            |
  | :-------- | :-------- | :---------------------------- | :------------ | :------------------------------------ |
  | `id`      | `Int`     | Scalar                        | -             | `@id` and `@default(autoincrement())` |
  | `email`   | `String`  | Scalar                        | -             | `@unique`                             |
  | `name`    | `String`  | Scalar                        | `?`           | -                                     |
  | `role`    | `Role`    | Scalar (`enum`)               | -             | `@default(USER)`                      |
  | `posts`   | `Post`    | Relation (Prisma-level field) | `[]`          | -                                     |
  | `profile` | `Profile` | Relation (Prisma-level field) | `?`           | -                                     |
</details>

Scalar fields [#scalar-fields]

The following example extends the `Comment` and `Tag` models with several scalar types. Some fields include [attributes](#defining-attributes):

  

#### Relational databases

```prisma highlight=2-4,8;normal 
model Comment {
  id      Int    @id @default(autoincrement()) // [!code highlight]
  title   String // [!code highlight]
  content String // [!code highlight]
}

model Tag {
  name String @id // [!code highlight]
}
```

#### MongoDB

```prisma highlight=2-4,8;normal 
model Comment {
  id      String @id @default(auto()) @map("_id") @db.ObjectId // [!code highlight]
  title   String // [!code highlight]
  content String // [!code highlight]
}

model Tag {
  name String @id @map("_id") // [!code highlight]
}
```

See [complete list of scalar field types](/orm/v6/reference/prisma-schema-reference#model-field-scalar-types) .

Relation fields [#relation-fields]

A relation field's type is another model - for example, a post (`Post`) can have multiple comments (`Comment[]`):

  

#### Relational databases

```prisma highlight=4,10;normal 
model Post {
  id       Int       @id @default(autoincrement())
  // Other fields
  comments Comment[] // A post can have many comments // [!code highlight]
}

model Comment {
  id     Int
  // Other fields
  post   Post? @relation(fields: [postId], references: [id]) // A comment can have one post // [!code highlight]
  postId Int?
}
```

#### MongoDB

```prisma highlight=4,10;normal 
model Post {
  id       String    @id @default(auto()) @map("_id") @db.Objectid
  // Other fields
  comments Comment[] // A post can have many comments // [!code highlight]
}

model Comment {
  id     String  @id @default(auto()) @map("_id") @db.Objectid
  // Other fields
  post   Post?   @relation(fields: [postId], references: [id]) // A comment can have one post // [!code highlight]
  postId String? @db.ObjectId
}
```

Refer to the [relations documentation](/orm/v6/prisma-schema/data-model/relations) for more examples and information about relationships between models.

Native types mapping [#native-types-mapping]

Version [2.17.0](https://github.com/prisma/prisma/releases/tag/2.17.0) and later support **native database type attributes** (type attributes) that describe the underlying database type:

```prisma highlight=3;normal
model Post {
  id      Int    @id
  title   String @db.VarChar(200) // [!code highlight]
  content String
}
```

Type attributes are:

* Specific to the underlying provider - for example, PostgreSQL uses `@db.Boolean` for `Boolean` whereas MySQL uses `@db.TinyInt(1)`
* Written in PascalCase (for example, `VarChar` or `Text`)
* Prefixed by `@db`, where `db` is the name of the `datasource` block in your schema

Furthermore, during [Introspection](/orm/v6/prisma-schema/introspection) type attributes are *only* added to the schema if the underlying native type is **not the default type**. For example, if you are using the PostgreSQL provider, `String` fields where the underlying native type is `text` will not have a type attribute.

See [complete list of native database type attributes per scalar type and provider](/orm/v6/reference/prisma-schema-reference#model-field-scalar-types) .

Benefits and workflows [#benefits-and-workflows]

* Control **the exact native type** that [Prisma Migrate](/orm/v6/prisma-migrate/getting-started) creates in the database - for example, a `String` can be `@db.VarChar(200)` or `@db.Char(50)`
* See an **enriched schema** when you introspect

Type modifiers [#type-modifiers]

The type of a field can be modified by appending either of two modifiers:

* [`[]`](/orm/v6/reference/prisma-schema-reference#-modifier) Make a field a list
* [`?`](/orm/v6/reference/prisma-schema-reference#-modifier-1) Make a field optional

> **Note**: You **cannot** combine type modifiers - optional lists are not supported.

Lists [#lists]

The following example includes a scalar list and a list of related models:

  

#### Relational databases

```prisma highlight=4,5;normal 
model Post {
  id       Int       @id @default(autoincrement())
  // Other fields
  comments Comment[] // A list of comments // [!code highlight]
  keywords String[] // A scalar list // [!code highlight]
}
```

#### MongoDB

```prisma highlight=4,5;normal 
model Post {
  id       String    @id @default(auto()) @map("_id") @db.ObjectId
  // Other fields
  comments Comment[] // A list of comments // [!code highlight]
  keywords String[] // A scalar list // [!code highlight]
}
```

> **Note**: Scalar lists are **only** supported if the database connector supports scalar lists, either natively or at a Prisma ORM level.

Optional and mandatory fields [#optional-and-mandatory-fields]

  

#### Relational databases

```prisma highlight=4;normal 
model Comment {
  id      Int     @id @default(autoincrement())
  title   String
  content String? // [!code highlight]
}

model Tag {
  name String @id
}
```

#### MongoDB

```prisma highlight=4;normal 
model Comment {
  id      String  @id @default(auto()) @map("_id") @db.ObjectId
  title   String
  content String? // [!code highlight]
}

model Tag {
  name String @id @map("_id")
}
```

When **not** annotating a field with the `?` type modifier, the field will be *required* on every record of the model. This has effects on two levels:

* **Databases**
  * **Relational databases**: Required fields are represented via `NOT NULL` constraints in the underlying database.
  * **MongoDB**: Required fields are not a concept on a MongoDB database level.
* **Prisma Client**: Prisma Client's generated [TypeScript types](#type-definitions) that represent the models in your application code will also define these fields as required to ensure they always carry values at runtime.

> **Note**: The default value of an optional field is `null`.

Unsupported types [#unsupported-types]

When you introspect a relational database, unsupported data types are added as [`Unsupported`](/orm/v6/reference/prisma-schema-reference#unsupported) :

```prisma
location    Unsupported("POLYGON")?
```

The `Unsupported` type allows you to define fields in the Prisma schema for database types that are not yet supported by Prisma ORM. For example, MySQL's `POLYGON` type is not currently supported by Prisma ORM, but can now be added to the Prisma schema using the `Unsupported("POLYGON")` type.

Fields of type `Unsupported` do not appear in the generated Prisma Client API, but you can still use Prisma ORM’s [raw database access feature](/orm/v6/prisma-client/using-raw-sql/raw-queries) to query these fields.

> **Note**: If a model has **mandatory `Unsupported` fields**, the generated client will not include `create` or `update` methods for that model.

> **Note**: The MongoDB connector does not support nor require the `Unsupported` type because it supports all scalar types.

Defining attributes [#defining-attributes]

Attributes modify the behavior of fields or model blocks. The following example includes three field attributes ([`@id`](/orm/v6/reference/prisma-schema-reference#id) , [`@default`](/orm/v6/reference/prisma-schema-reference#default) , and [`@unique`](/orm/v6/reference/prisma-schema-reference#unique) ) and one block attribute ([`@@unique`](/orm/v6/reference/prisma-schema-reference#unique-1)):

  

#### Relational databases

```prisma
model User {
  id        Int     @id @default(autoincrement())
  firstName String
  lastName  String
  email     String  @unique
  isAdmin   Boolean @default(false)

  @@unique([firstName, lastName])
}
```

#### MongoDB

```prisma
model User {
  id        String  @id @default(auto()) @map("_id") @db.ObjectId
  firstName String
  lastName  String
  email     String  @unique
  isAdmin   Boolean @default(false)

  @@unique([firstName, lastName])
}
```

Some attributes accept [arguments](/orm/v6/reference/prisma-schema-reference#attribute-argument-types) - for example, `@default` accepts `true` or `false`:

```prisma
isAdmin   Boolean @default(false) // short form of @default(value: false)
```

See [complete list of field and block attributes](/orm/v6/reference/prisma-schema-reference#attributes)

Defining an ID field [#defining-an-id-field]

An ID uniquely identifies individual records of a model. A model can only have *one* ID:

* In **relational databases**, the ID can be a single field or based on multiple fields. If a model does not have an `@id` or an `@@id`, you must define a mandatory `@unique` field or `@@unique` block instead.
* In **MongoDB**, an ID must be a single field that defines an `@id` attribute and a `@map("_id")` attribute.

Defining IDs in relational databases [#defining-ids-in-relational-databases]

In relational databases, an ID can be defined by a single field using the [`@id`](/orm/v6/reference/prisma-schema-reference#id) attribute, or multiple fields using the [`@@id`](/orm/v6/reference/prisma-schema-reference#id-1) attribute.

Single field IDs [#single-field-ids]

In the following example, the `User` ID is represented by the `id` integer field:

```prisma highlight=2;normal
model User {
  id      Int      @id @default(autoincrement()) // [!code highlight]
  email   String   @unique
  name    String?
  role    Role     @default(USER)
  posts   Post[]
  profile Profile?
}
```

Composite IDs [#composite-ids]

In the following example, the `User` ID is represented by a combination of the `firstName` and `lastName` fields:

```prisma highlight=7;normal
model User {
  firstName String
  lastName  String
  email     String  @unique
  isAdmin   Boolean @default(false)

  @@id([firstName, lastName]) // [!code highlight]
}
```

By default, the name of this field in Prisma Client queries will be `firstName_lastName`.

You can also provide your own name for the composite ID using the [`@@id`](/orm/v6/reference/prisma-schema-reference#id-1) attribute's `name` field:

```prisma highlight=7;normal
model User {
  firstName String
  lastName  String
  email     String  @unique
  isAdmin   Boolean @default(false)

  @@id(name: "fullName", fields: [firstName, lastName]) // [!code highlight]
}
```

The `firstName_lastName` field will now be named `fullName` instead.

> [!NOTE]
> Refer to the documentation on [working with composite IDs](/orm/v6/prisma-client/special-fields-and-types/working-with-composite-ids-and-constraints) to learn how to interact with a composite ID in Prisma Client.

@unique fields as unique identifiers [#unique-fields-as-unique-identifiers]

In the following example, users are uniquely identified by a `@unique` field. Because the `email` field functions as a unique identifier for the model (which is required), it must be mandatory:

```prisma highlight=2;normal
model User {
  email   String   @unique // [!code highlight]
  name    String?
  role    Role     @default(USER)
  posts   Post[]
  profile Profile?
}
```

> [!NOTE]
> **Constraint names in relational databases** <br />
> You can optionally define a [custom primary key constraint name](/orm/v6/prisma-schema/data-model/database-mapping#constraint-and-index-names) in the underlying database.

Defining IDs in MongoDB [#defining-ids-in-mongodb]

The MongoDB connector has [specific rules for defining an ID field](/orm/v6/reference/prisma-schema-reference#mongodb) that differs from relational databases. An ID must be defined by a single field using the [`@id`](/orm/v6/reference/prisma-schema-reference#id) attribute and must include `@map("_id")`.

In the following example, the `User` ID is represented by the `id` string field that accepts an auto-generated `ObjectId`:

```prisma highlight=2;normal
model User {
  id      String   @id @default(auto()) @map("_id") @db.ObjectId // [!code highlight]
  email   String   @unique
  name    String?
  role    Role     @default(USER)
  posts   Post[]
  profile Profile?
}
```

In the following example, the `User` ID is represented by the `id` string field that accepts something other than an `ObjectId` - for example, a unique username:

```prisma highlight=2;normal
model User {
  id      String   @id @map("_id") // [!code highlight]
  email   String   @unique
  name    String?
  role    Role     @default(USER)
  posts   Post[]
  profile Profile?
}
```

> [!WARNING]
> **MongoDB does not support `@@id`**<br />
> MongoDB does not support composite IDs, which means you cannot identify a model with a `@@id` block.

Defining a default value [#defining-a-default-value]

You can define default values for scalar fields of your models using the [`@default`](/orm/v6/reference/prisma-schema-reference#default) attribute:

  

#### Relational databases

```prisma highlight=3,5;normal 
model Post {
  id         Int        @id @default(autoincrement())
  createdAt  DateTime   @default(now()) // [!code highlight]
  title      String
  published  Boolean    @default(false) // [!code highlight]
  data       Json       @default("{ \"hello\": \"world\" }") // [!code highlight]
  author     User       @relation(fields: [authorId], references: [id])
  authorId   Int
  categories Category[] @relation(references: [id])
}
```

#### MongoDB

```prisma highlight=3,5;normal 
model Post {
  id         String     @id @default(auto()) @map("_id") @db.ObjectId
  createdAt  DateTime   @default(now())
  title      String
  published  Boolean    @default(false)
  author     User       @relation(fields: [authorId], references: [id])
  authorId   String     @db.ObjectId
  categories Category[] @relation(references: [id])
}
```

`@default` attributes either:

* Represent `DEFAULT` values in the underlying database (relational databases only) *or*
* Use a Prisma ORM-level function. For example, `cuid()` and `uuid()` are provided by Prisma Client's [query engine](/orm/v6/more/internals/engines) for all connectors.

Default values can be:

* Static values that correspond to the field type, such as `5` (`Int`), `Hello` (`String`), or `false` (`Boolean`)
* [Lists](/orm/v6/reference/prisma-schema-reference#-modifier) of static values, such as `[5, 6, 8]` (`Int[]`) or `["Hello", "Goodbye"]` (`String`\[]). These are available in Prisma ORM versions `4.0.0` and later, when using supported databases (PostgreSQL, CockroachDB and MongoDB)
* [Functions](#using-functions), such as [`now()`](/orm/v6/reference/prisma-schema-reference#now) or [`uuid()`](/orm/v6/reference/prisma-schema-reference#uuid)
* JSON data. Note that JSON needs to be enclosed with double-quotes inside the `@default` attribute, e.g.: `@default("[]")`. If you want to provide a JSON object, you need to enclose it with double-quotes and then escape any internal double quotes using a backslash, e.g.: `@default("{ \"hello\": \"world\" }")`.

> [!NOTE]
> Refer to the [attribute function reference documentation](/orm/v6/reference/prisma-schema-reference#attribute-functions) for information about connector support for functions.

Defining a unique field [#defining-a-unique-field]

You can add unique attributes to your models to be able to uniquely identify individual records of that model. Unique attributes can be defined on a single field using [`@unique`](/orm/v6/reference/prisma-schema-reference#unique) attribute, or on multiple fields (also called composite or compound unique constraints) using the [`@@unique`](/orm/v6/reference/prisma-schema-reference#unique-1) attribute.

In the following example, the value of the `email` field must be unique:

  

#### Relational databases

```prisma
model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String?
}
```

#### MongoDB

```prisma
model User {
  id    String  @id @default(auto()) @map("_id") @db.ObjectId
  email String  @unique
  name  String?
}
```

In the following example, a combination of `authorId` and `title` must be unique:

  

#### Relational databases

```prisma highlight=10;normal 
model Post {
  id         Int        @id @default(autoincrement())
  createdAt  DateTime   @default(now())
  title      String
  published  Boolean    @default(false)
  author     User       @relation(fields: [authorId], references: [id])
  authorId   Int
  categories Category[] @relation(references: [id])

  @@unique([authorId, title]) // [!code highlight]
}
```

#### MongoDB

```prisma highlight=10;normal 
model Post {
  id         String     @id @default(auto()) @map("_id") @db.ObjectId
  createdAt  DateTime   @default(now())
  title      String
  published  Boolean    @default(false)
  author     User       @relation(fields: [authorId], references: [id])
  authorId   String     @db.ObjectId
  categories Category[] @relation(references: [id])

  @@unique([authorId, title]) // [!code highlight]
}
```

> [!NOTE]
> **Constraint names in relational databases** <br />
> You can optionally define a [custom unique constraint name](/orm/v6/prisma-schema/data-model/database-mapping#constraint-and-index-names) in the underlying database.

By default, the name of this field in Prisma Client queries will be `authorId_title`.

You can also provide your own name for the composite unique constraint using the [`@@unique`](/orm/v6/prisma-schema/data-model/database-mapping#constraint-and-index-names) attribute's `name` field:

```prisma highlight=10;normal
model Post {
  id         String     @id @default(auto()) @map("_id") @db.ObjectId
  createdAt  DateTime   @default(now())
  title      String
  published  Boolean    @default(false)
  author     User       @relation(fields: [authorId], references: [id])
  authorId   String     @db.ObjectId
  categories Category[] @relation(references: [id])

  @@unique(name: "authorTitle", [authorId, title]) // [!code highlight]
}
```

The `authorId_title` field will now be named `authorTitle` instead.

> [!NOTE]
> Refer to the documentation on [working with composite unique identifiers](/orm/v6/prisma-client/special-fields-and-types/working-with-composite-ids-and-constraints) to learn how to interact with a composite unique constraints in Prisma Client.

Composite type unique constraints [#composite-type-unique-constraints]

When using the MongoDB provider in version `3.12.0` and later, you can define a unique constraint on a field of a [composite type](#defining-composite-types) using the syntax `@@unique([compositeType.field])`. As with other fields, composite type fields can be used as part of a multi-column unique constraint.

The following example defines a multi-column unique constraint based on the `email` field of the `User` model and the `number` field of the `Address` composite type which is used in `User.address`:

```prisma title="schema.prisma" showLineNumbers
type Address {
  street String
  number Int
}

model User {
  id      Int     @id
  email   String
  address Address

  @@unique([email, address.number])
}
```

This notation can be chained if there is more than one nested composite type:

```prisma title="schema.prisma" showLineNumbers
type City {
  name String
}

type Address {
  number Int
  city   City
}

model User {
  id      Int       @id
  address Address[]

  @@unique([address.city.name])
}
```

Defining an index [#defining-an-index]

You can define indexes on one or multiple fields of your models via the [`@@index`](/orm/v6/reference/prisma-schema-reference#index) on a model. The following example defines a multi-column index based on the `title` and `content` field:

```prisma
model Post {
  id      Int     @id @default(autoincrement())
  title   String
  content String?

  @@index([title, content])
}
```

> [!NOTE]
> **Index names in relational databases** <br />
> You can optionally define a [custom index name](/orm/v6/prisma-schema/data-model/database-mapping#constraint-and-index-names) in the underlying database.

Defining composite type indexes [#defining-composite-type-indexes]

When using the MongoDB provider in version `3.12.0` and later, you can define an index on a field of a [composite type](#defining-composite-types) using the syntax `@@index([compositeType.field])`. As with other fields, composite type fields can be used as part of a multi-column index.

The following example defines a multi-column index based on the `email` field of the `User` model and the `number` field of the `Address` composite type:

```prisma title="schema.prisma" showLineNumbers
type Address {
  street String
  number Int
}

model User {
  id      Int     @id
  email   String
  address Address

  @@index([email, address.number])
}
```

This notation can be chained if there is more than one nested composite type:

```prisma title="schema.prisma" showLineNumbers
type City {
  name String
}

type Address {
  number Int
  city   City
}

model User {
  id      Int       @id
  address Address[]

  @@index([address.city.name])
}
```

Defining enums [#defining-enums]

You can define enums in your data model [if enums are supported for your database connector](/orm/v6/reference/database-features#misc), either natively or at Prisma ORM level.

Enums are considered [scalar](#scalar-fields) types in the Prisma schema data model. They're therefore [by default](/orm/v6/prisma-client/queries/select-fields#return-the-default-fields) included as return values in [Prisma Client queries](/orm/v6/prisma-client/queries/crud).

Enums are defined via the [`enum`](/orm/v6/reference/prisma-schema-reference#enum) block. For example, a `User` has a `Role`:

  

#### Relational databases

```prisma highlight=5,8-11;normal 
model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String?
  role  Role    @default(USER) // [!code highlight]
}

enum Role { // [!code highlight]
  USER // [!code highlight]
  ADMIN // [!code highlight]
} // [!code highlight]
```

#### MongoDB

```prisma highlight=5,8-11;normal 
model User {
  id    String  @id @default(auto()) @map("_id") @db.ObjectId
  email String  @unique
  name  String?
  role  Role    @default(USER) // [!code highlight]
}

enum Role { // [!code highlight]
  USER // [!code highlight]
  ADMIN // [!code highlight]
} // [!code highlight]
```

Defining composite types [#defining-composite-types]

> [!NOTE]
> Composite types were added in version `3.10.0` under the `mongodb` Preview feature flag and are in General Availability since version `3.12.0`.

> [!WARNING]
> Composite types are currently only available on MongoDB.

Composite types (known as [embedded documents](https://www.mongodb.com/docs/manual/data-modeling/#embedded-data) in MongoDB) provide support for embedding records inside other records, by allowing you to define new object types. Composite types are structured and typed in a similar way to [models](#defining-models).

To define a composite type, use the `type` block. As an example, take the following schema:

```prisma title="schema.prisma" showLineNumbers
model Product {
  id     String  @id @default(auto()) @map("_id") @db.ObjectId
  name   String
  photos Photo[]
}

type Photo {
  height Int
  width  Int
  url    String
}
```

In this case, the `Product` model has a list of `Photo` composite types stored in `photos`.

Considerations when using composite types [#considerations-when-using-composite-types]

Composite types only support a limited set of [attributes](/orm/v6/reference/prisma-schema-reference#attributes). The following attributes are supported:

* `@default`
* `@map`
* [Native types](/orm/v6/reference/prisma-schema-reference#model-field-scalar-types), such as `@db.ObjectId`

The following attributes are not supported inside composite types:

* `@unique`
* `@id`
* `@relation`
* `@ignore`
* `@updatedAt`

However, unique constraints can still be defined by using the `@@unique` attribute on the level of the model that uses the composite type. For more details, see [Composite type unique constraints](#composite-type-unique-constraints).

Indexes can be defined by using the `@@index` attribute on the level of the model that uses the composite type. For more details, see [Composite type indexes](#defining-composite-type-indexes).

Using functions [#using-functions]

The Prisma schema supports a number of [functions](/orm/v6/reference/prisma-schema-reference#attribute-functions) . These can be used to specify [default values](/orm/v6/reference/prisma-schema-reference#default) on fields of a model.

For example, the default value of `createdAt` is [`now()`](/orm/v6/reference/prisma-schema-reference#now) :

  

#### Relational databases

```prisma
model Post {
  id        Int      @id @default(autoincrement())
  createdAt DateTime @default(now())
}
```

#### MongoDB

```prisma
model Post {
  id        String   @default(auto()) @map("_id") @db.ObjectId
  createdAt DateTime @default(now())
}
```

[`cuid()`](/orm/v6/reference/prisma-schema-reference#cuid) and [`uuid()`](/orm/v6/reference/prisma-schema-reference#uuid) are implemented by Prisma ORM and therefore are not "visible" in the underlying database schema. You can still use them when using [introspection](/orm/v6/prisma-schema/introspection) by [manually changing your Prisma schema](/orm/v6/prisma-client/setup-and-configuration/custom-model-and-field-names) and [generating Prisma Client](/orm/v6/prisma-client/setup-and-configuration/generating-prisma-client), in that case the values will be generated by Prisma Client's [query engine](/orm/v6/more/internals/engines)

Support for [`autoincrement()`](/orm/v6/reference/prisma-schema-reference#autoincrement), [`now()`](/orm/v6/reference/prisma-schema-reference#now), and [`dbgenerated(...)`](/orm/v6/reference/prisma-schema-reference#dbgenerated) differ between databases.

**Relational database connectors** implement `autoincrement()`, `dbgenerated(...)`, and `now()` at database level. The **MongoDB connector** does not support `autoincrement()` or `dbgenerated(...)`, and `now()` is implemented at the Prisma ORM level. The [`auto()`](/orm/v6/reference/prisma-schema-reference#auto) function is used to generate an `ObjectId`.

Relations [#relations]

Refer to the [relations documentation](/orm/v6/prisma-schema/data-model/relations) for more examples and information about relationships between models.

Models in Prisma Client [#models-in-prisma-client]

Queries (CRUD) [#queries-crud]

Every model in the data model definition will result in a number of CRUD queries in the generated [Prisma Client API](/orm/v6/prisma-client/setup-and-configuration/introduction):

* [`findMany()`](/orm/v6/reference/prisma-client-reference#findmany)
* [`findFirst()`](/orm/v6/reference/prisma-client-reference#findfirst)
* [`findFirstOrThrow()`](/orm/v6/reference/prisma-client-reference#findfirstorthrow)
* [`findUnique()`](/orm/v6/reference/prisma-client-reference#findunique)
* [`findUniqueOrThrow()`](/orm/v6/reference/prisma-client-reference#finduniqueorthrow)
* [`create()`](/orm/v6/reference/prisma-client-reference#create)
* [`update()`](/orm/v6/reference/prisma-client-reference#update)
* [`upsert()`](/orm/v6/reference/prisma-client-reference#upsert)
* [`delete()`](/orm/v6/reference/prisma-client-reference#delete)
* [`createMany()`](/orm/v6/reference/prisma-client-reference#createmany)
* [`createManyAndReturn()`](/orm/v6/reference/prisma-client-reference#createmanyandreturn)
* [`updateMany()`](/orm/v6/reference/prisma-client-reference#updatemany)
* [`updateManyAndReturn()`](/orm/v6/reference/prisma-client-reference#updatemanyandreturn)
* [`deleteMany()`](/orm/v6/reference/prisma-client-reference#deletemany)

The operations are accessible via a generated property on the Prisma Client instance. By default the name of the property is the lowercase form of the model name, e.g. `user` for a `User` model or `post` for a `Post` model.

Here is an example illustrating the use of a `user` property from the Prisma Client API:

```js
const newUser = await prisma.user.create({
  data: {
    name: "Alice",
  },
});
const allUsers = await prisma.user.findMany();
```

Type definitions [#type-definitions]

Prisma Client also generates **type definitions** that reflect your model structures. These are part of the generated [`@prisma/client`](/orm/v6/prisma-client/setup-and-configuration/generating-prisma-client#the-prismaclient-npm-package) node module.

When using TypeScript, these type definitions ensure that all your database queries are entirely type safe and validated at compile-time (even partial queries using [`select`](/orm/v6/reference/prisma-client-reference#select) or [`include`](/orm/v6/reference/prisma-client-reference#include) ).

Even when using plain JavaScript, the type definitions are still included in the `@prisma/client` node module, enabling features like [IntelliSense](https://code.visualstudio.com/docs/editor/intellisense)/autocompletion in your editor.

> **Note**: The actual types are stored in the `.prisma/client` folder. `@prisma/client/index.d.ts` exports the contents of this folder.

For example, the type definition for the `User` model from above would look as follows:

```ts
export type User = {
  id: number;
  email: string;
  name: string | null;
  role: string;
};
```

Note that the relation fields `posts` and `profile` are not included in the type definition by default. However, if you need variations of the `User` type you can still define them using some of [Prisma Client's generated helper types](/orm/v6/prisma-client/setup-and-configuration/generating-prisma-client) (in this case, these helper types would be called `UserGetIncludePayload` and `UserGetSelectPayload`).

Limitations [#limitations]

Records must be uniquely identifiable [#records-must-be-uniquely-identifiable]

Prisma ORM currently only supports models that have at least one unique field or combination of fields. In practice, this means that every Prisma model must have either at least one of the following attributes:

* `@id` or `@@id` for a single- or multi-field primary key constraint (max one per model)
* `@unique` or `@@unique` for a single- or multi-field unique constraint

## Related pages

- [`Database mapping`](https://www.prisma.io/docs/orm/v6/prisma-schema/data-model/database-mapping): Database mapping in Prisma schema
- [`External tables`](https://www.prisma.io/docs/orm/v6/prisma-schema/data-model/externally-managed-tables): How to declare and use externally managed tables in Prisma ORM
- [`Indexes`](https://www.prisma.io/docs/orm/v6/prisma-schema/data-model/indexes): How to configure index functionality and add full text indexes
- [`Multi-schema`](https://www.prisma.io/docs/orm/v6/prisma-schema/data-model/multi-schema): How to use Prisma ORM with multiple database schemas
- [`Relations`](https://www.prisma.io/docs/orm/v6/prisma-schema/data-model/relations): A relation is a connection between two models in the Prisma schema. This page explains how you can define one-to-one, one-to-many and many-to-many relations in Prisma.