diff --git a/cSpell.json b/cSpell.json
index f5513a8282..d10b82d345 100644
--- a/cSpell.json
+++ b/cSpell.json
@@ -91,6 +91,7 @@
"Aiven",
"Ania",
"Koyeb",
+ "Inngest",
"Neward",
"nikolasburk",
"Slonik",
@@ -111,7 +112,9 @@
"Hyperdrive",
"pgcat",
"JAFNSZHQRDTW",
- "BCAA"
+ "BCAA",
+ "Turborepo",
+ "Deepgram"
],
"patterns": [
{
diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-cockroachdb.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-cockroachdb.mdx
index 044496fef8..206037cbf6 100644
--- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-cockroachdb.mdx
+++ b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-cockroachdb.mdx
@@ -19,7 +19,7 @@ Learn how to add Prisma ORM to an existing Node.js or TypeScript project by conn
:::tip
-If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/orm/more/migrating-to-prisma/migrate-from-typeorm) or [Migrate from Sequelize](/orm/more/migrating-to-prisma/migrate-from-sequelize) migration guides.
+If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/guides/migrate-from-typeorm) or [Migrate from Sequelize](/guides/migrate-from-sequelize) migration guides.
:::
diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-mysql.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-mysql.mdx
index a97e93f194..e6548a530a 100644
--- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-mysql.mdx
+++ b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-mysql.mdx
@@ -19,7 +19,7 @@ Learn how to add Prisma ORM to an existing Node.js or TypeScript project by conn
:::tip
-If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/orm/more/migrating-to-prisma/migrate-from-typeorm) or [Migrate from Sequelize](/orm/more/migrating-to-prisma/migrate-from-sequelize) migration guides.
+If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/guides/migrate-from-typeorm) or [Migrate from Sequelize](/guides/migrate-from-sequelize) migration guides.
:::
diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-planetscale.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-planetscale.mdx
index e45d720cb5..3b768d1381 100644
--- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-planetscale.mdx
+++ b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-planetscale.mdx
@@ -19,7 +19,7 @@ Learn how to add Prisma ORM to an existing Node.js or TypeScript project by conn
:::tip
-If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/orm/more/migrating-to-prisma/migrate-from-typeorm) or [Migrate from Sequelize](/orm/more/migrating-to-prisma/migrate-from-sequelize) migration guides.
+If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/guides/migrate-from-typeorm) or [Migrate from Sequelize](/guides/migrate-from-sequelize) migration guides.
:::
diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-postgresql.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-postgresql.mdx
index 5550111651..1d9cc5f6c9 100644
--- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-postgresql.mdx
+++ b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-postgresql.mdx
@@ -20,7 +20,7 @@ Learn how to add Prisma ORM to an existing Node.js or TypeScript project by conn
:::tip
-If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/orm/more/migrating-to-prisma/migrate-from-typeorm) or [Migrate from Sequelize](/orm/more/migrating-to-prisma/migrate-from-sequelize) migration guides.
+If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/guides/migrate-from-typeorm) or [Migrate from Sequelize](/guides/migrate-from-sequelize) migration guides.
:::
diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-sqlserver.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-sqlserver.mdx
index b3751c438e..3bb4479fe7 100644
--- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-sqlserver.mdx
+++ b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-node-sqlserver.mdx
@@ -19,7 +19,7 @@ Learn how to add Prisma ORM to an existing Node.js or TypeScript project by conn
:::tip
-If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/orm/more/migrating-to-prisma/migrate-from-typeorm) or [Migrate from Sequelize](/orm/more/migrating-to-prisma/migrate-from-sequelize) migration guides.
+If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/guides/migrate-from-typeorm) or [Migrate from Sequelize](/guides/migrate-from-sequelize) migration guides.
:::
diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-cockroachdb.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-cockroachdb.mdx
index 6616d7ecb0..7ede2c9a68 100644
--- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-cockroachdb.mdx
+++ b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-cockroachdb.mdx
@@ -20,7 +20,7 @@ Learn how to add Prisma ORM to an existing Node.js or TypeScript project by conn
:::tip
-If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/orm/more/migrating-to-prisma/migrate-from-typeorm) or [Migrate from Sequelize](/orm/more/migrating-to-prisma/migrate-from-sequelize) migration guides.
+If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/guides/migrate-from-typeorm) or [Migrate from Sequelize](/guides/migrate-from-sequelize) migration guides.
:::
diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-mysql.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-mysql.mdx
index 6f5277a5cd..3d23794a20 100644
--- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-mysql.mdx
+++ b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-mysql.mdx
@@ -19,7 +19,7 @@ Learn how to add Prisma ORM to an existing Node.js or TypeScript project by conn
:::tip
-If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/orm/more/migrating-to-prisma/migrate-from-typeorm) or [Migrate from Sequelize](/orm/more/migrating-to-prisma/migrate-from-sequelize) migration guides.
+If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/guides/migrate-from-typeorm) or [Migrate from Sequelize](/guides/migrate-from-sequelize) migration guides.
:::
diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-planetscale.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-planetscale.mdx
index 49f10e1998..9a1d8d1b9d 100644
--- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-planetscale.mdx
+++ b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-planetscale.mdx
@@ -19,7 +19,7 @@ Learn how to add Prisma ORM to an existing Node.js or TypeScript project by conn
:::tip
-If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/orm/more/migrating-to-prisma/migrate-from-typeorm) or [Migrate from Sequelize](/orm/more/migrating-to-prisma/migrate-from-sequelize) migration guides.
+If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/guides/migrate-from-typeorm) or [Migrate from Sequelize](/guides/migrate-from-sequelize) migration guides.
:::
diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-postgresql.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-postgresql.mdx
index c687836f8d..ba927b16d6 100644
--- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-postgresql.mdx
+++ b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-postgresql.mdx
@@ -19,7 +19,7 @@ Learn how to add Prisma ORM to an existing Node.js or TypeScript project by conn
:::tip
-If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/orm/more/migrating-to-prisma/migrate-from-typeorm) or [Migrate from Sequelize](/orm/more/migrating-to-prisma/migrate-from-sequelize) migration guides.
+If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/guides/migrate-from-typeorm) or [Migrate from Sequelize](/guides/migrate-from-sequelize) migration guides.
:::
diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-sqlserver.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-sqlserver.mdx
index 2db50dee76..d107d61e9f 100644
--- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-sqlserver.mdx
+++ b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/110-relational-databases-typescript-sqlserver.mdx
@@ -19,7 +19,7 @@ Learn how to add Prisma ORM to an existing Node.js or TypeScript project by conn
:::tip
-If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/orm/more/migrating-to-prisma/migrate-from-typeorm) or [Migrate from Sequelize](/orm/more/migrating-to-prisma/migrate-from-sequelize) migration guides.
+If you're migrating to Prisma ORM from another ORM, see our [Migrate from TypeORM](/guides/migrate-from-typeorm) or [Migrate from Sequelize](/guides/migrate-from-sequelize) migration guides.
:::
diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb-node-mongodb.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb-node-mongodb.mdx
index 74b7d74ec5..e9a8cc1cb1 100644
--- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb-node-mongodb.mdx
+++ b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb-node-mongodb.mdx
@@ -15,7 +15,7 @@ Learn how to add Prisma ORM to an existing Node.js or TypeScript project by conn
-If you're migrating to Prisma ORM from Mongoose, see our [Migrate from Mongoose guide](/orm/more/migrating-to-prisma/migrate-from-mongoose).
+If you're migrating to Prisma ORM from Mongoose, see our [Migrate from Mongoose guide](/guides/migrate-from-mongoose).
diff --git a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb-typescript-mongodb.mdx b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb-typescript-mongodb.mdx
index c5a37914c0..cdf9d06110 100644
--- a/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb-typescript-mongodb.mdx
+++ b/content/100-getting-started/02-setup-prisma/200-add-to-existing-project/120-mongodb-typescript-mongodb.mdx
@@ -15,7 +15,7 @@ Learn how to add Prisma ORM to an existing Node.js or TypeScript project by conn
-If you're migrating to Prisma ORM from Mongoose, see our [Migrate from Mongoose guide](/orm/more/migrating-to-prisma/migrate-from-mongoose).
+If you're migrating to Prisma ORM from Mongoose, see our [Migrate from Mongoose guide](/guides/migrate-from-mongoose).
diff --git a/content/200-orm/050-overview/500-databases/950-cloudflare-d1.mdx b/content/200-orm/050-overview/500-databases/950-cloudflare-d1.mdx
index 39316a077d..5c57a35bdc 100644
--- a/content/200-orm/050-overview/500-databases/950-cloudflare-d1.mdx
+++ b/content/200-orm/050-overview/500-databases/950-cloudflare-d1.mdx
@@ -12,7 +12,7 @@ This guide discusses the concepts behind using Prisma ORM and Cloudflare D1, exp
Prisma ORM support for Cloudflare D1 is currently in [Preview](/orm/more/releases#preview). We would appreciate your feedback [on GitHub](https://github.com/prisma/prisma/discussions/23646).
-If you want to deploy a Cloudflare Worker with D1 and Prisma ORM, follow this [tutorial](/orm/prisma-client/deployment/edge/deploy-to-cloudflare#cloudflare-d1).
+If you want to deploy a Cloudflare Worker with D1 and Prisma ORM, follow this [tutorial](/guides/using-prisma-orm-with-cloudflare-d1).
@@ -45,7 +45,7 @@ There are a number of differences between D1 and SQLite to consider. You should
When using Prisma ORM with D1, you need to use the `sqlite` database provider and the `@prisma/adapter-d1` [driver adapter](/orm/overview/databases/database-drivers#driver-adapters).
-If you want to deploy a Cloudflare Worker with D1 and Prisma ORM, follow these [step-by-step instructions](/orm/prisma-client/deployment/edge/deploy-to-cloudflare#cloudflare-d1).
+If you want to deploy a Cloudflare Worker with D1 and Prisma ORM, follow these [step-by-step instructions](/guides/using-prisma-orm-with-cloudflare-d1).
## Migration workflows
diff --git a/content/200-orm/200-prisma-client/500-deployment/301-edge/100-overview.mdx b/content/200-orm/200-prisma-client/500-deployment/301-edge/100-overview.mdx
index 2b6d0ea9b5..65bf1f967f 100644
--- a/content/200-orm/200-prisma-client/500-deployment/301-edge/100-overview.mdx
+++ b/content/200-orm/200-prisma-client/500-deployment/301-edge/100-overview.mdx
@@ -50,7 +50,7 @@ Depending on which deployment provider and database/driver you use, there may be
- [PostgreSQL (traditional)](/orm/prisma-client/deployment/edge/deploy-to-cloudflare#postgresql-traditional)
- [PlanetScale](/orm/prisma-client/deployment/edge/deploy-to-cloudflare#planetscale)
- [Neon](/orm/prisma-client/deployment/edge/deploy-to-cloudflare#neon)
- - [Cloudflare D1](/orm/prisma-client/deployment/edge/deploy-to-cloudflare#cloudflare-d1)
+ - [Cloudflare D1](/guides/using-prisma-orm-with-cloudflare-d1)
- Vercel
- [Vercel Postgres](/orm/prisma-client/deployment/edge/deploy-to-vercel#vercel-postgres)
- [Neon](/orm/prisma-client/deployment/edge/deploy-to-vercel#neon)
diff --git a/content/200-orm/200-prisma-client/500-deployment/301-edge/450-deploy-to-cloudflare.mdx b/content/200-orm/200-prisma-client/500-deployment/301-edge/450-deploy-to-cloudflare.mdx
index 416f683d96..1ee14a80c1 100644
--- a/content/200-orm/200-prisma-client/500-deployment/301-edge/450-deploy-to-cloudflare.mdx
+++ b/content/200-orm/200-prisma-client/500-deployment/301-edge/450-deploy-to-cloudflare.mdx
@@ -23,7 +23,7 @@ The edge-compatible drivers for Cloudflare Workers and Pages are:
- [PlanetScale Serverless](https://planetscale.com/docs/tutorials/planetscale-serverless-driver) uses HTTP to access the database
- [`node-postgres`](https://node-postgres.com/) (`pg`) uses Cloudflare's `connect()` (TCP) to access the database
- [`@libsql/client`](https://github.com/tursodatabase/libsql-client-ts) is used to access Turso databases via HTTP
-- [Cloudflare D1](/orm/prisma-client/deployment/edge/deploy-to-cloudflare#cloudflare-d1) is used to access D1 databases
+- [Cloudflare D1](/orm/prisma-client/deployment/edge/deploy-to-cloudflare) is used to access D1 databases
There's [also work being done](https://github.com/sidorares/node-mysql2/pull/2289) on the `node-mysql2` driver which will enable access to traditional MySQL databases from Cloudflare Workers and Pages in the future as well.
@@ -538,201 +538,4 @@ Then you can go ahead then deploy the Worker:
npx wrangler deploy
```
-The command will output the URL where you can access the deployed Worker.
-
-### Cloudflare D1
-
-If you are using a D1 database, you need to:
-
-- use the `@prisma/adapter-d1` database adapter (via the `driverAdapters` Preview feature)
-- set `sqlite` as the `datasource` provider in your Prisma schema
-- manually generate SQL statements for schema changes using `prisma migrate diff` but execute them using [D1's migration system](https://developers.cloudflare.com/d1/reference/migrations/)
-
-You can find a [deployment-ready example on GitHub](https://github.com/prisma/prisma-examples/blob/latest/deployment-platforms/edge/cloudflare-workers/with-d1).
-
-#### 1. Configure Prisma schema
-
-> **Note**: If you don't have a project to deploy, follow the instructions in the [Prerequisites](#prerequisites) to bootstrap a basic Cloudflare Worker with Prisma ORM in it.
-
-In your Prisma schema, add the `driverAdapters` Preview feature to the `generator` block and set the `provider` of the `datasource` to `sqlite`. If you just bootstrapped the Prisma schema with `prisma init`, also be sure to add the following `User` model to it:
-
-```prisma file=schema.prisma
-generator client {
- provider = "prisma-client-js"
- previewFeatures = ["driverAdapters"]
-}
-
-datasource db {
- provider = "sqlite"
- url = env("DATABASE_URL")
-}
-
-model User {
- id Int @id @default(autoincrement())
- email String @unique
- name String?
-}
-```
-
-Note that in this tutorial, you won't need the `.env` file since the connection between Prisma ORM and D1 will happen through a [binding](https://developers.cloudflare.com/workers/configuration/bindings/).
-
-#### 2. Install dependencies
-
-Next, install the required packages:
-
-```terminal
-npm install @prisma/adapter-d1
-```
-
-Also, be sure to use a version of the Wrangler CLI that's above [`wrangler@^3.39.0`](https://github.com/cloudflare/workers-sdk/releases/tag/wrangler%403.39.0), otherwise the `--remote` flag that's used in the next sections won't be available.
-
-#### 3. Set the D1 database connection via a binding
-
-To connect your Workers with the D1 instance, add the following binding to your `wrangler.toml` (if you don't have a D1 instance yet, you can create one using the [Cloudflare Dashboard](https://dash.cloudflare.com/) or with the [`wrangler d1 create`](https://developers.cloudflare.com/workers/wrangler/commands/#create) command):
-
-```toml file=wrangler.toml
-name = "prisma-cloudflare-worker-example"
-main = "src/index.ts"
-compatibility_date = "2024-03-20"
-compatibility_flags = ["nodejs_compat"]
-
-[[d1_databases]]
-binding = "DB" # i.e. available in your Worker on env.DB
-database_name = "__YOUR_D1_DATABASE_NAME__" # to be replaced
-database_id = "__YOUR_D1_DATABASE_ID__" # to be replaced
-```
-
-Note that `__YOUR_D1_DATABASE_NAME__` and `__YOUR_D1_DATABASE_ID__` in the snippet above are placeholders that should be replaced with the database name and ID of your own D1 instance.
-
-If you weren't able to grab this ID from the terminal output, you can also find it in the Cloudflare Dashboard or by running `npx wrangler d1 list` and `npx wrangler d1 info __YOUR_D1_DATABASE_NAME__` in your terminal.
-
-#### 4. Migrate your database schema (if applicable)
-
-If your Prisma schema only contains the `User` model but your D1 database is still empty, you need to make sure that there is a table in D1 that mirrors the structure of the `User` model.
-
-D1 comes with its own [migration system](https://developers.cloudflare.com/d1/reference/migrations/) that lets you manage migration files in your file system. While this is convenient for creating and applying migration files, it doesn't help you identifying the actual SQL statements that you need to put into these migration files. That's where Prisma Migrate comes into play, because you can generate SQL statements for schema changes using the [`prisma migrate diff`](/orm/reference/prisma-cli-reference#migrate-diff) command.
-
-First, create the `migrations` directory and initial migration file using the [`wrangler d1 migrations`](https://developers.cloudflare.com/workers/wrangler/commands/#migrations-create) command as follows:
-
-```terminal
-npx wrangler d1 migrations create __YOUR_D1_DATABASE_NAME__ create_user_table
-```
-
-Replace `__YOUR_D1_DATABASE_NAME__` with the name of your database again and, when prompted, confirm that you want to create the `migrations` directory. After having run this command, there should be a new folder called `migrations` with a file called `0001_create_user_table.sql` inside of it.
-
-You can now generate the required SQL statement for creating a `User` table that can be mapped to the `User` model in your the Prisma schema as follows:
-
-```terminal
-npx prisma migrate diff --from-empty --to-schema-datamodel ./prisma/schema.prisma --script --output migrations/0001_create_user_table.sql
-```
-
-Note that the resulting SQL statement is stored in a file in the `migrations` directory called `0001_create_user_table.sql` which looks as follows:
-
-```sql file=migrations/0001_create_user_table.sql no-copy
--- CreateTable
-CREATE TABLE "User" (
- "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
- "email" TEXT NOT NULL,
- "name" TEXT
-);
-
--- CreateIndex
-CREATE UNIQUE INDEX "User_email_key" ON "User"("email");
-```
-
-You now need to use the [`wrangler d1 migrations apply`](https://developers.cloudflare.com/workers/wrangler/commands/#migrations-apply) command to send this SQL statement to D1. Note that this command accepts two options:
-
-- `--local`: Executes the statement against a _local_ version of D1. This local version of D1 is a SQLite database file that'll be located in your project. This approach is useful, when you want to develop and test your Worker on your local machine. Learn more in the [Cloudflare docs](https://developers.cloudflare.com/d1/build-with-d1/local-development/).
-- `--remote`: Executes the statement against your _remote_ version of D1. This version is used by your _deployed_ Cloudflare Workers. Learn more in the [Cloudflare docs](https://developers.cloudflare.com/d1/build-with-d1/remote-development/).
-
-In this tutorial, you'll do both: test the Worker locally _and_ deploy it afterwards. So, you need to run both commands. Open your terminal and paste the following commands:
-
-```terminal
-# For the local database
-npx wrangler d1 migrations apply __YOUR_D1_DATABASE_NAME__ --local
-
-# For the remote database
-npx wrangler d1 migrations apply __YOUR_D1_DATABASE_NAME__ --remote
-```
-
-As before, you need to replace `__YOUR_D1_DATABASE_NAME__` with the name of your D1 database.
-
-Let's also create some dummy data that we can query once the Worker is running. This time, you'll run the SQL statement without storing it in a file:
-
-```terminal
-# For the local database
-npx wrangler d1 execute __YOUR_D1_DATABASE_NAME__ --command "INSERT INTO \"User\" (\"email\", \"name\") VALUES
-('jane@prisma.io', 'Jane Doe (Local)');" --local
-
-# For the remote database
-npx wrangler d1 execute __YOUR_D1_DATABASE_NAME__ --command "INSERT INTO \"User\" (\"email\", \"name\") VALUES
-('jane@prisma.io', 'Jane Doe (Remote)');" --remote
-```
-
-#### 5. Use Prisma Client in your Worker to send a query to the database
-
-Before adding a Prisma Client query to your Worker, you need to generate Prisma Client with the following command:
-
-```
-npx prisma generate
-```
-
-In order to query your database from the Worker using Prisma ORM, you need to:
-
-1. Add the `DB` binding to the `Env` interface. (Alternatively, you can run [`npx wrangler types`](https://developers.cloudflare.com/workers/wrangler/commands/#types) to generate the `Env` type from the binding in a separate file called `worker-configuration.d.ts`.)
-2. Instantiate `PrismaClient` using the `PrismaD1` driver adapter.
-3. Send a query using Prisma Client and return the result.
-
-Open `src/index.ts` and replace the entire content with the following:
-
-```typescript file=src/index.ts
-import { PrismaClient } from '@prisma/client'
-import { PrismaD1 } from '@prisma/adapter-d1'
-
-export interface Env {
- DB: D1Database
-}
-
-export default {
- async fetch(
- request: Request,
- env: Env,
- ctx: ExecutionContext
- ): Promise {
- const adapter = new PrismaD1(env.DB)
- const prisma = new PrismaClient({ adapter })
-
- const users = await prisma.user.findMany()
- const result = JSON.stringify(users)
- return new Response(result)
- },
-}
-```
-
-#### 6. Run the Worker locally
-
-With the database query in place and Prisma Client generated, you can go ahead and run the Worker locally:
-
-```
-npm run dev
-```
-
-Now you can open your browser at [`http://localhost:8787`](http://localhost:8787/) to see the result of the database query:
-
-```js no-copy
-;[{ id: 1, email: 'jane@prisma.io', name: 'Jane Doe (Local)' }]
-```
-
-#### 7. Set the `DATABASE_URL` environment variable and deploy the Worker
-
-To deploy the Worker, run the the following command:
-
-```
-npm run deploy
-```
-
-Your deployed Worker is accessible via `https://prisma-d1-example.USERNAME.workers.dev`. If you navigate your browser to that URL, you should see the following data that's queried from your remote D1 database:
-
-```js no-copy
-;[{ id: 1, email: 'jane@prisma.io', name: 'Jane Doe (Remote)' }]
-```
+The command will output the URL where you can access the deployed Worker.
\ No newline at end of file
diff --git a/content/200-orm/300-prisma-migrate/300-workflows/100-team-development.mdx b/content/200-orm/300-prisma-migrate/300-workflows/100-team-development.mdx
index cce0dc57a8..7ea0aaf727 100644
--- a/content/200-orm/300-prisma-migrate/300-workflows/100-team-development.mdx
+++ b/content/200-orm/300-prisma-migrate/300-workflows/100-team-development.mdx
@@ -5,207 +5,4 @@ metaDescription: How to use Prisma Migrate when collaborating on a project as a
toc_max_heading_level: 2
---
-
-
-To incorporate changes from collaborators:
-
-1. Pull the changed Prisma schema and `./prisma/migrations` folder
-1. Run the `migrate dev` command to apply new migrations:
-
- ```terminal
- npx prisma migrate dev
- ```
-
-Migrations are **applied in the same order as they were created**. The creation date is part of the migration subfolder name - for example, `20210316081837-updated-fields` was created on `2021-03-16-08:18:37`.
-
-
-
-This guide **does not apply for MongoDB**.
-Instead of `migrate dev`, [`db push`](/orm/prisma-migrate/workflows/prototyping-your-schema) is used for [MongoDB](/orm/overview/databases/mongodb).
-
-
-
-
-
-## Example: Incorporating your team's changes
-
-The following sample scenario demonstrates how a team of three developers share and incorporate changes to the Prisma schema and the migration history.
-
-The following tabs show the team's Prisma schema before and after a round of changes:
-
-
-
-
-
-```prisma file=schema.prisma
-model Post {
- id Int @id @default(autoincrement())
- title String
- content String?
- published Boolean @default(false)
- author User? @relation(fields: [authorId], references: [id])
- authorId Int?
-}
-
-model User {
- id Int @id @default(autoincrement())
- email String @unique
- name String?
- posts Post[]
-}
-```
-
-
-
-
-
-```prisma file=schema.prisma highlight=14,15,19-23;add
-model Post {
- id Int @id @default(autoincrement())
- title String
- content String?
- published Boolean @default(false)
- author User? @relation(fields: [authorId], references: [id])
- authorId Int?
-}
-
-model User {
- id Int @id @default(autoincrement())
- email String @unique
- name String?
- //add-start
- favoriteColor String? // Added by Ania
- bestPacmanScore Int? // Added by you
- //add-end
- posts Post[]
-}
-
-//add-start
-// Added by Javier
-model Tag {
- tagName String @id
- tagCategory Category
-}
-//add-end
-```
-
-
-
-
-### The team's changes
-
-Your team members Ania and Javier make additive changes to the schema in their local environment and generate migrations.
-
-**Ania** makes the following changes:
-
-1. Adds a model field:
-
- ```prisma highlight=3;add
- model User {
- /* ... */
- //add-next-line
- favoriteColor String?
- }
- ```
-
-1. Generates a migration:
-
- ```terminal
- npx prisma migrate dev --name new-field
- ```
-
-1. Commits the changed schema and the new migration:
-
- - `./prisma/schema.prisma`
- - `./prisma/migrations/20210316081837-new-field/migration.sql`
-
-**Javier** makes the following changes:
-
-1. Adds a new model to the schema:
-
- ```prisma highlight=1-4;add
- //add-start
- model Tag {
- tagName String @id
- tagCategory Category
- }
- //add-end
- ```
-
-1. Generates a migration:
-
- ```terminal
- npx prisma migrate dev --name new-model
- ```
-
-1. Commits the changed schema and the new migration:
-
- - `./prisma/schema.prisma`
- - `./prisma/migrations/20210316091837-new-model/migration.sql`
-
-The migration history now has **two** new migrations:
-
-
-
-### Integrating changes
-
-**You** want to incorporate your team's changes. To do that, you:
-
-1. Pull the most recent changes from your team, including:
-
- - Two new migrations:
-
- - `./prisma/migrations/20210316081837-new-field/migration.sql`
- - `./prisma/migrations/20210316091837-new-model/migration.sql`
-
- - An updated schema file. Git automatically merges the updated schema with _your_ local schema changes (a new `bestPacmanScore` field):
-
- ```prisma highlight=3,7-11;add
- model User {
- /* ... */
- //add-next-line
- favoriteColor String?
- bestPacmanScore Int?
- }
-
- //add-start
- model Tag {
- tagName String @id
- tagCategory Category
- posts Post[]
- }
- //add-end
- ```
-
-1. Run the `migrate dev` command:
-
- ```terminal
- npx prisma migrate dev
- ```
-
- 1. Applies Ania and Javier's migrations to your local database.
-
- - `./prisma/migrations/20210316081837-new-field/migration.sql`
- - `./prisma/migrations/20210316091837-new-model/migration.sql`
-
- 1. Creates a new migration with your changes, prompts you to name it (`pacman-field`), and applies the new migration to your local database:
-
- - `./prisma/migrations/20210322081837-pacman-field/migration.sql`
-
-1. Commit the merged `schema.prisma` and your new migration: `./prisma/migrations/20210322081837-pacman-field/migration.sql`
-
-Your `schema.prisma` and local database now include your team's changes, and the migration history includes your migration:
-
-
-
-## Source control
-
-You should commit the following files to source control:
-
-- The contents of the `.prisma/migrations` folder, including the `migration_lock.toml` file
-- The Prisma Schema (`schema.prisma`)
-
-Source-controlling the `schema.prisma` file is not enough - you must include your migration history. This is because:
-
-- As you start to [customize migrations](/orm/prisma-migrate/workflows/customizing-migrations), your migration history contains **information that cannot be represented in the Prisma schema**. For example, you can customize a migration to mitigate data loss that would be caused by a breaking change.
-- The `prisma migrate deploy` command, which is used to deploy changes to staging, testing, and production environments, _only_ runs migration files. Prisma Migrate only uses the schema to read the `url` and `provider` fields, not models and fields.
+This guide has been moved to the [guides section](/guides/implementing-schema-changes). You can find the guide there.
diff --git a/content/200-orm/300-prisma-migrate/300-workflows/45-data-migration.mdx b/content/200-orm/300-prisma-migrate/300-workflows/45-data-migration.mdx
index eb471f0114..d7a4f4b235 100644
--- a/content/200-orm/300-prisma-migrate/300-workflows/45-data-migration.mdx
+++ b/content/200-orm/300-prisma-migrate/300-workflows/45-data-migration.mdx
@@ -1,260 +1,6 @@
---
title: Data migrations
metaDescription: How to migrate data using Prisma ORM with the expand and contract pattern.
-tocDepth: 3
---
-
-
-Prisma ORM does not yet natively support data migrations, but you can use the [expand and contract pattern](https://www.prisma.io/dataguide/types/relational/expand-and-contract-pattern) to migrate your data. For example from one column into another.
-
-This guide covers how you can use Prisma ORM with the expand and contract pattern to:
-
-- Expand your schema with a new column
-- Create and run the data migration
-- Contract your schema by dropping the old column
-
-
-
-## Overview of the steps
-
-This tutorial will walk you through the following steps:
-
-1. Expand your schema with a new column
-1. Create and run the data migration file
-1. Contract your schema by dropping the old column
-
-It also makes the following assumptions:
-
-- The production database is accessible from the development machine
-- `prisma migrate dev` is only run against development database
-- The expanding and contracting steps are handled in separate branches
-
-For this guide, you will modify the following schema by replacing the `published` boolean field with a `status` enum:
-
-```prisma file=prisma/schema.prisma showLineNumbers
-generator client {
- provider = "prisma-client-js"
-}
-
-datasource db {
- provider = "postgresql"
- url = env("DATABASE_URL")
-}
-
-model Post {
- id Int @id @default(autoincrement())
- title String
- content String?
- published Boolean @default(false)
-}
-```
-
-## Expand your schema with a new column
-
-Checkout to a new branch from your `main` branch:
-
-```terminal
-git checkout -b create-status-field
-```
-
-Make the following updates to your Prisma schema:
-
-- Create a `Status` enum with the following values: `Unknown`, `Draft`, `InReview`, and `Published`
-- Add a `status` column to the `Post` model
-- Mark the `published` field as optional
-
-```prisma file=prisma/schema.prisma highlight=5,6,9-15;edit showLineNumbers
-model Post {
- id Int @id @default(autoincrement())
- title String
- content String?
- //edit-start
- published Boolean? @default(false)
- status Status
- //edit-end
-}
-
-enum Status {
- Unknown
- Draft
- InProgress
- InReview
- Published
-}
-```
-
-Create a new migration to sync the Prisma schema with the database schema:
-
-```terminal
-npx prisma migrate dev --name add-status-column
-```
-
-Prisma Migrate will give you the following warning because the field being added to the database is non-nullable, and the database contains existing data which require a default value.
-
-
-
-
-
-```no-copy
-Prisma schema loaded from prisma/schema.prisma
-Datasource "db": PostgreSQL database "data-migration", schema "public" at "localhost:5401"
-
-Error:
-⚠️ We found changes that cannot be executed:
-
- • Step 1 Added the required column `status` to the `Post` table without a default value. There are 4 rows in this table, it is not possible to execute this step.
-
-You can use prisma migrate dev --create-only to create the migration file, and manually modify it to address the underlying issue(s).
-Then run prisma migrate dev to apply it and verify it works.
-```
-
-
-
-
-Exit from the migration step and update the schema by adding a default value for the `status` field by adding the `@default()` attribute function.
-
-```prisma file=prisma/schema.prisma highlight=6;edit showLineNumbers
-model Post {
- id Int @id @default(autoincrement())
- title String
- content String?
- published Boolean? @default(false)
- //edit-next-line
- status Status @default(Unknown)
-}
-
-enum Status {
- Unknown
- Draft
- InProgress
- InReview
- Published
-}
-```
-
-Generate and execute the migration using the following command:
-
-```terminal
-npx prisma migrate dev --name add-default
-```
-
-## Create and run the data migration file
-
-### Create a data migration file
-
-Inside the generated migration folder from the previous step, create a file called `data-migration.ts` file. This file will contain a data migration which will be implemented using Prisma Client.
-
-Add the following code to migrate the data from the `published` field to the `status` field in the file you just created:
-
-```ts file=prisma/migrations/20230417131956_add-status-column/data-migration.ts
-import { PrismaClient } from '@prisma/client'
-
-const prisma = new PrismaClient()
-
-async function main() {
- await prisma.$transaction(async (tx) => {
- const posts = await tx.post.findMany()
- for (const post of posts) {
- await tx.post.update({
- where: { id: post.id },
- data: {
- status: post.published ? 'Published' : 'Unknown',
- },
- })
- }
- })
-}
-
-main()
- .catch(async (e) => {
- console.error(e)
- process.exit(1)
- })
- .finally(async () => await prisma.$disconnect())
-```
-
-The data migration is wrapped in a transaction to ensure that the query is rolled back, allowing you to iterate on your data migration file
-
-Next steps:
-
-1. Push your changes to a remote origin and create a new pull request.
-1. Once you’re happy with the changes, merge the changes to your `main` branch.
-
-To apply the changes to your production database, add `prisma migrate deploy` as part of your deployment/ build step in CI
-
-### Run the data migration
-
-Update the `package.json` file with the script to execute the data-migration file. Be sure to update the `20230417131956_add-status-column` with the name of your migration file.
-
-```json file=package.json
-"scripts": {
- "dev": "tsx ./script.ts",
- "data-migration:add-status-column": "tsx ./prisma/migrations/20230417131956_add-status-column/data-migration.ts"
- },
-```
-
-Next steps:
-
-1. Push your changes to a remote origin and create a new pull request.
-1. Once you’re happy with the changes, merge the changes to your “main” branch.
-
-To apply the changes to your production database, add `prisma migrate deploy` as part of your deployment/ build step in CI.
-
-### Run the data migration
-
-Update the `DATABASE_URL` environment variable with your production database's URL. Run the data migration script:
-
-```terminal
-npm run data-migration:add-status-column
-```
-
-## Contract your schema by dropping the old column
-
-Checkout to a separate branch on your development machine:
-
-```terminal
-git checkout -b drop-published-column
-```
-
-Delete the `published` field from your schema and generate a new migration:
-
-```prisma highlight=5;delete
-model Post {
- id Int @id @default(autoincrement())
- title String
- content String?
- //delete-next-line
- published Boolean? @default(false)
- status Status @default(Unknown)
-}
-
-enum Status {
- Draft
- InProgress
- InReview
- Published
-}
-```
-
-Generate a new migration:
-
-```terminal
-npx prisma migrate dev --name drop-published-column
-```
-
-Next steps:
-
-1. Push your changes to a remote origin and create a new pull request.
-1. Once you’re happy with the changes, merge the changes to your `main` branch.
-
-To apply the changes to your production database, add `prisma migrate deploy` as part of your deployment/ build step in CI
-
-```terminal
-npx prisma migrate deploy
-```
-
-You have successfully:
-
-- Migrated data from the `published` to `status` column
-- Dropped the `published` column from your schema
+This guide has been moved to our new [guides section](/guides/data-migration-with-expand-and-contract). You can find the guide there.
diff --git a/content/200-orm/800-more/400-comparisons/01-prisma-and-typeorm.mdx b/content/200-orm/800-more/400-comparisons/01-prisma-and-typeorm.mdx
index 40265bb19f..157ec754f9 100644
--- a/content/200-orm/800-more/400-comparisons/01-prisma-and-typeorm.mdx
+++ b/content/200-orm/800-more/400-comparisons/01-prisma-and-typeorm.mdx
@@ -4,7 +4,7 @@ metaTitle: 'Prisma ORM vs TypeORM'
metaDescription: 'Learn how Prisma compares to TypeORM.'
---
-This page compares Prisma ORM and [TypeORM](https://typeorm.io/). If you want to learn how to migrate from TypeORM to Prisma ORM, check out this [guide](/orm/more/migrating-to-prisma/migrate-from-typeorm).
+This page compares Prisma ORM and [TypeORM](https://typeorm.io/). If you want to learn how to migrate from TypeORM to Prisma ORM, check out this [guide](/guides/migrate-from-typeorm).
## TypeORM vs Prisma ORM
diff --git a/content/200-orm/800-more/400-comparisons/03-prisma-and-mongoose.mdx b/content/200-orm/800-more/400-comparisons/03-prisma-and-mongoose.mdx
index 1584e64982..ba6361eb23 100644
--- a/content/200-orm/800-more/400-comparisons/03-prisma-and-mongoose.mdx
+++ b/content/200-orm/800-more/400-comparisons/03-prisma-and-mongoose.mdx
@@ -6,7 +6,7 @@ metaDescription: 'Learn how Prisma ORM compares to Mongoose.'
-This page compares the Prisma ORM and [Mongoose](https://mongoosejs.com/docs/guide.html) APIs. If you want to learn how to migrate from Mongoose to Prisma, check out this [guide](/orm/more/migrating-to-prisma/migrate-from-mongoose).
+This page compares the Prisma ORM and [Mongoose](https://mongoosejs.com/docs/guide.html) APIs. If you want to learn how to migrate from Mongoose to Prisma, check out this [guide](/guides/migrate-from-mongoose).
diff --git a/content/200-orm/800-more/450-migrating-to-prisma/01-migrate-from-typeorm.mdx b/content/200-orm/800-more/450-migrating-to-prisma/01-migrate-from-typeorm.mdx
deleted file mode 100644
index efeddfdbbf..0000000000
--- a/content/200-orm/800-more/450-migrating-to-prisma/01-migrate-from-typeorm.mdx
+++ /dev/null
@@ -1,1143 +0,0 @@
----
-title: 'Migrate from TypeORM'
-metaTitle: 'How to migrate from TypeORM to Prisma ORM'
-metaDescription: 'Learn how to migrate from TypeORM to Prisma ORM'
----
-
-
-
-This guide describes how to migrate from TypeORM to Prisma ORM. It uses an extended version of the [TypeORM Express example](https://github.com/typeorm/typescript-express-example/) as a [sample project](https://github.com/prisma/migrate-from-typeorm-to-prisma) to demonstrate the migration steps. You can find the example used for this guide on [GitHub](https://github.com/prisma/migrate-from-typeorm-to-prisma).
-
-This migration guide uses PostgreSQL as the example database, but it equally applies to any other relational database that's [supported by Prisma ORM](/orm/reference/supported-databases).
-
-You can learn how Prisma ORM compares to TypeORM on the [Prisma ORM vs TypeORM](/orm/more/comparisons/prisma-and-typeorm) page.
-
-
-
-## Overview of the migration process
-
-Note that the steps for migrating from TypeORM to Prisma ORM are always the same, no matter what kind of application or API layer you're building:
-
-1. Install the Prisma CLI
-1. Introspect your database
-1. Create a baseline migration
-1. Install Prisma Client
-1. Gradually replace your TypeORM queries with Prisma Client
-
-These steps apply, no matter if you're building a REST API (e.g. with Express, koa or NestJS), a GraphQL API (e.g. with Apollo Server, TypeGraphQL or Nexus) or any other kind of application that uses TypeORM for database access.
-
-Prisma ORM lends itself really well for **incremental adoption**. This means, you don't have migrate your entire project from TypeORM to Prisma ORM at once, but rather you can _step-by-step_ move your database queries from TypeORM to Prisma ORM.
-
-## Overview of the sample project
-
-For this guide, we'll use a REST API built with Express as a [sample project](https://github.com/prisma/migrate-from-typeorm-to-prisma) to migrate to Prisma ORM. It has four models/entities:
-
-
-
-
-
-```ts
-@Entity()
-export class User {
- @PrimaryGeneratedColumn()
- id: number
-
- @Column({ nullable: true })
- name: string
-
- @Column({ unique: true })
- email: string
-
- @OneToMany((type) => Post, (post) => post.author)
- posts: Post[]
-
- @OneToOne((type) => Profile, (profile) => profile.user, { cascade: true })
- profile: Profile
-}
-```
-
-
-
-
-
-```ts
-@Entity()
-export class Post {
- @PrimaryGeneratedColumn()
- id: number
-
- @Column()
- title: string
-
- @Column({ nullable: true })
- content: string
-
- @Column({ default: false })
- published: boolean
-
- @ManyToOne((type) => User, (user) => user.posts)
- author: User
-
- @ManyToMany((type) => Category, (category) => category.posts)
- @JoinTable()
- categories: Category[]
-}
-```
-
-
-
-
-
-```ts
-@Entity()
-export class Profile {
- @PrimaryGeneratedColumn()
- id: number
-
- @Column({ nullable: true })
- bio: string
-
- @OneToOne((type) => User, (user) => user.profile)
- @JoinColumn()
- user: User
-}
-```
-
-
-
-
-
-```ts
-@Entity()
-export class Category {
- @PrimaryGeneratedColumn()
- id: number
-
- @Column()
- name: string
-
- @ManyToMany((type) => Post, (post) => post.categories)
- posts: Post[]
-}
-```
-
-
-
-
-
-The models have the following relations:
-
-- 1-1: `User` ↔ `Profile`
-- 1-n: `User` ↔ `Post`
-- m-n: `Post` ↔ `Category`
-
-The corresponding tables have been created using a generated TypeORM migration.
-
-
-
-Expand to view details of the migration
-
-The migration has been created using
-
-```terminal
-typeorm migration:generate -n Init
-```
-
-This created the following migration file:
-
-```ts file=migrations/1605698662257-Init.ts
-import { MigrationInterface, QueryRunner } from 'typeorm'
-
-export class Init1605698662257 implements MigrationInterface {
- name = 'Init1605698662257'
-
- public async up(queryRunner: QueryRunner): Promise {
- await queryRunner.query(
- `CREATE TABLE "profile" ("id" SERIAL NOT NULL, "bio" character varying, "userId" integer, CONSTRAINT "REL_a24972ebd73b106250713dcddd" UNIQUE ("userId"), CONSTRAINT "PK_3dd8bfc97e4a77c70971591bdcb" PRIMARY KEY ("id"))`
- )
- await queryRunner.query(
- `CREATE TABLE "user" ("id" SERIAL NOT NULL, "name" character varying, "email" character varying NOT NULL, CONSTRAINT "UQ_e12875dfb3b1d92d7d7c5377e22" UNIQUE ("email"), CONSTRAINT "PK_cace4a159ff9f2512dd42373760" PRIMARY KEY ("id"))`
- )
- await queryRunner.query(
- `CREATE TABLE "post" ("id" SERIAL NOT NULL, "title" character varying NOT NULL, "content" character varying, "published" boolean NOT NULL DEFAULT false, "authorId" integer, CONSTRAINT "PK_be5fda3aac270b134ff9c21cdee" PRIMARY KEY ("id"))`
- )
- await queryRunner.query(
- `CREATE TABLE "category" ("id" SERIAL NOT NULL, "name" character varying NOT NULL, CONSTRAINT "PK_9c4e4a89e3674fc9f382d733f03" PRIMARY KEY ("id"))`
- )
- await queryRunner.query(
- `CREATE TABLE "post_categories_category" ("postId" integer NOT NULL, "categoryId" integer NOT NULL, CONSTRAINT "PK_91306c0021c4901c1825ef097ce" PRIMARY KEY ("postId", "categoryId"))`
- )
- await queryRunner.query(
- `CREATE INDEX "IDX_93b566d522b73cb8bc46f7405b" ON "post_categories_category" ("postId") `
- )
- await queryRunner.query(
- `CREATE INDEX "IDX_a5e63f80ca58e7296d5864bd2d" ON "post_categories_category" ("categoryId") `
- )
- await queryRunner.query(
- `ALTER TABLE "profile" ADD CONSTRAINT "FK_a24972ebd73b106250713dcddd9" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`
- )
- await queryRunner.query(
- `ALTER TABLE "post" ADD CONSTRAINT "FK_c6fb082a3114f35d0cc27c518e0" FOREIGN KEY ("authorId") REFERENCES "user"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`
- )
- await queryRunner.query(
- `ALTER TABLE "post_categories_category" ADD CONSTRAINT "FK_93b566d522b73cb8bc46f7405bd" FOREIGN KEY ("postId") REFERENCES "post"("id") ON DELETE CASCADE ON UPDATE NO ACTION`
- )
- await queryRunner.query(
- `ALTER TABLE "post_categories_category" ADD CONSTRAINT "FK_a5e63f80ca58e7296d5864bd2d3" FOREIGN KEY ("categoryId") REFERENCES "category"("id") ON DELETE CASCADE ON UPDATE NO ACTION`
- )
- }
-
- public async down(queryRunner: QueryRunner): Promise {
- await queryRunner.query(
- `ALTER TABLE "post_categories_category" DROP CONSTRAINT "FK_a5e63f80ca58e7296d5864bd2d3"`
- )
- await queryRunner.query(
- `ALTER TABLE "post_categories_category" DROP CONSTRAINT "FK_93b566d522b73cb8bc46f7405bd"`
- )
- await queryRunner.query(
- `ALTER TABLE "post" DROP CONSTRAINT "FK_c6fb082a3114f35d0cc27c518e0"`
- )
- await queryRunner.query(
- `ALTER TABLE "profile" DROP CONSTRAINT "FK_a24972ebd73b106250713dcddd9"`
- )
- await queryRunner.query(`DROP INDEX "IDX_a5e63f80ca58e7296d5864bd2d"`)
- await queryRunner.query(`DROP INDEX "IDX_93b566d522b73cb8bc46f7405b"`)
- await queryRunner.query(`DROP TABLE "post_categories_category"`)
- await queryRunner.query(`DROP TABLE "category"`)
- await queryRunner.query(`DROP TABLE "post"`)
- await queryRunner.query(`DROP TABLE "user"`)
- await queryRunner.query(`DROP TABLE "profile"`)
- }
-}
-```
-
-
-
-As mentioned before, this guide is an extended variation of the TypeORM Express example and uses the same file structure. The route handlers are located in the `src/controller` directory. From there, they are pulled into a central `src/routes.ts` file which is used to set up the required routes in `src/index.ts`:
-
-```
-└── blog-typeorm
- ├── ormconfig.json
- ├── package.json
- ├── src
- │ ├── controllers
- │ │ ├── AddPostToCategoryAction.ts
- │ │ ├── CreateDraftAction.ts
- │ │ ├── CreateUserAction.ts
- │ │ ├── FeedAction.ts
- │ │ ├── FilterPostsAction.ts
- │ │ ├── GetPostByIdAction.ts
- │ │ └── SetBioForUserAction.ts
- │ ├── entity
- │ │ ├── Category.ts
- │ │ ├── Post.ts
- │ │ ├── Profile.ts
- │ │ └── User.ts
- │ ├── index.ts
- │ ├── migration
- │ │ └── 1605698662257-Init.ts
- │ └── routes.ts
- └── tsconfig.json
-```
-
-## Step 1. Install the Prisma CLI
-
-The first step to adopt Prisma ORM is to [install the Prisma CLI](/orm/tools/prisma-cli#installation) in your project:
-
-```terminal copy
-npm install prisma --save-dev
-```
-
-## Step 2. Introspect your database
-
-### 2.1. Set up Prisma ORM
-
-Before you can introspect your database, you need to set up your [Prisma schema](/orm/prisma-schema) and connect Prisma to your database. Run the following command in your terminal to create a basic Prisma schema file:
-
-```terminal copy
-npx prisma init
-```
-
-This command created a new directory called `prisma` with the following files for you:
-
-- `schema.prisma`: Your Prisma schema that specifies your database connection and models
-- `.env`: A [`dotenv`](https://github.com/motdotla/dotenv) to configure your database connection URL as an environment variable
-
-The Prisma schema currently looks as follows:
-
-```prisma file=prisma/schema.prisma showLineNumbers
-// This is your Prisma schema file,
-// learn more about it in the docs: https://pris.ly/d/prisma-schema
-
-datasource db {
- provider = "postgresql"
- url = env("DATABASE_URL")
-}
-
-generator client {
- provider = "prisma-client-js"
-}
-```
-
-:::tip
-
-If you're using VS Code, be sure to install the [Prisma VS Code extension](https://marketplace.visualstudio.com/items?itemName=Prisma.prisma) for syntax highlighting, formatting, auto-completion and a lot more cool features.
-
-:::
-
-### 2.2. Connect your database
-
-If you're not using PostgreSQL, you need to adjust the `provider` field on the `datasource` block to the database you currently use:
-
-
-
-
-
-```prisma file=schema.prisma showLineNumbers
-datasource db {
- provider = "postgresql"
- url = env("DATABASE_URL")
-}
-```
-
-
-
-
-
-
-```prisma file=schema.prisma showLineNumbers
-datasource db {
- provider = "mysql"
- url = env("DATABASE_URL")
-}
-```
-
-
-
-
-
-
-```prisma file=schema.prisma showLineNumbers
-datasource db {
- provider = "sqlserver"
- url = env("DATABASE_URL")
-}
-```
-
-
-
-
-
-
-```prisma file=schema.prisma showLineNumbers
-datasource db {
- provider = "sqlite"
- url = env("DATABASE_URL")
-}
-```
-
-
-
-
-
-Once that's done, you can configure your [database connection URL](/orm/reference/connection-urls) in the `.env` file. Here's how the database connection from TypeORM maps to the connection URL format used by Prisma ORM:
-
-
-
-
-
-
-Assume you have the following database connection details in `ormconfig.json`:
-
-
-```json file=ormconfig.json showLineNumbers
-{
- "type": "postgres",
- "host": "localhost",
- "port": 5432,
- "username": "alice",
- "password": "myPassword42",
- "database": "blog-typeorm"
-}
-```
-
-
-The respective connection URL would look as follows in Prisma ORM:
-
-
-```env file=.env showLineNumbers
-DATABASE_URL="postgresql://alice:myPassword42@localhost:5432/blog-typeorm"
-```
-
-
-Note that you can optionally configure the PostgreSQL [schema](https://www.postgresql.org/docs/9.1/ddl-schemas.html) by appending the `schema` argument to the connection URL:
-
-
-```env file=.env showLineNumbers
-DATABASE_URL="postgresql://alice:myPassword42@localhost:5432/blog-typeorm?schema=myschema"
-```
-
-
-If not provided, the default schema called `public` is being used.
-
-
-
-
-
-
-
-Assume you have the following database connection details in `ormconfig.json`:
-
-
-```json file=ormconfig.json showLineNumbers
-{
- "type": "mysql",
- "host": "localhost",
- "port": 3306,
- "username": "alice",
- "password": "myPassword42",
- "database": "blog-typeorm"
-}
-```
-
-
-The respective connection URL would look as follows in Prisma:
-
-
-```env file=.env showLineNumbers
-DATABASE_URL="mysql://alice:myPassword42@localhost:3306/blog-typeorm"
-```
-
-
-
-
-
-
-Assume you have the following database connection details in `ormconfig.json`:
-
-
-```json file=ormconfig.json showLineNumbers
-{
- "type": "mssql",
- "host": "localhost",
- "port": 1433,
- "username": "alice",
- "password": "myPassword42",
- "database": "blog-typeorm"
-}
-```
-
-
-The respective connection URL would look as follows in Prisma:
-
-
-```env file=.env showLineNumbers
-DATABASE_URL="sqlserver://localhost:1433;database=blog-typeorm;user=alice;password=myPassword42;trustServerCertificate=true"
-```
-
-
-
-
-
-
-Assume you have the following database connection details in `ormconfig.json`:
-
-
-```json file=ormconfig.json showLineNumbers
-{
- "type": "sqlite",
- "database": "blog-typeorm"
-}
-```
-
-
-The respective connection URL would look as follows in Prisma:
-
-
-```env file=.env showLineNumbers
-DATABASE_URL="file:./blog-typeorm.db"
-```
-
-
-
-
-
-### 2.3. Introspect your database using Prisma ORM
-
-With your connection URL in place, you can [introspect](/orm/prisma-schema/introspection) your database to generate your Prisma models:
-
-```terminal copy
-npx prisma db pull
-```
-
-This creates the following Prisma models:
-
-```prisma file=prisma/schema.prisma showLineNumbers
-model typeorm_migrations {
- id Int @id @default(autoincrement())
- timestamp Int
- name String
-
- @@map("_typeorm_migrations")
-}
-
-model category {
- id Int @id @default(autoincrement())
- name String
- post_categories_category post_categories_category[]
-}
-
-model post {
- id Int @id @default(autoincrement())
- title String
- content String?
- published Boolean @default(false)
- authorId Int?
- user user? @relation(fields: [authorId], references: [id])
- post_categories_category post_categories_category[]
-}
-
-model post_categories_category {
- postId Int
- categoryId Int
- category category @relation(fields: [categoryId], references: [id])
- post post @relation(fields: [postId], references: [id])
-
- @@id([postId, categoryId])
- @@index([postId], name: "IDX_93b566d522b73cb8bc46f7405b")
- @@index([categoryId], name: "IDX_a5e63f80ca58e7296d5864bd2d")
-}
-
-model profile {
- id Int @id @default(autoincrement())
- bio String?
- userId Int? @unique
- user user? @relation(fields: [userId], references: [id])
-}
-
-model user {
- id Int @id @default(autoincrement())
- name String?
- email String @unique
- post post[]
- profile profile?
-}
-```
-
-The generated Prisma models represent your database tables and are the foundation for your programmatic Prisma Client API which allows you to send queries to your database.
-
-### 2.4. Create a baseline migration
-
-To continue using Prisma Migrate to evolve your database schema, you will need to [baseline your database](/orm/prisma-migrate/getting-started).
-
-First, create a `migrations` directory and add a directory inside with your preferred name for the migration. In this example, we will use `0_init` as the migration name:
-
-```terminal
-mkdir -p prisma/migrations/0_init
-```
-
-Next, generate the migration file with `prisma migrate diff`. Use the following arguments:
-
-- `--from-empty`: assumes the data model you're migrating from is empty
-- `--to-schema-datamodel`: the current database state using the URL in the `datasource` block
-- `--script`: output a SQL script
-
-```terminal wrap
-npx prisma migrate diff --from-empty --to-schema-datamodel prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql
-```
-
-Review the generated migration to ensure everything is correct.
-
-Next, mark the migration as applied using `prisma migrate resolve` with the `--applied` argument.
-
-```terminal
-npx prisma migrate resolve --applied 0_init
-```
-
-The command will mark `0_init` as applied by adding it to the `_prisma_migrations` table.
-
-You now have a baseline for your current database schema. To make further changes to your database schema, you can update your Prisma schema and use `prisma migrate dev` to apply the changes to your database.
-
-### 2.5. Adjust the Prisma schema (optional)
-
-The models that were generated via introspection currently _exactly_ map to your database tables. In this section, you'll learn how you can adjust the naming of the Prisma models to adhere to [Prisma ORM's naming conventions](/orm/reference/prisma-schema-reference#naming-conventions).
-
-All of these adjustment are entirely optional and you are free to skip to the next step already if you don't want to adjust anything for now. You can go back and make the adjustments at any later point.
-
-As opposed to the current snake_case notation of TypeORM models, Prisma ORM's naming conventions are:
-
-- PascalCase for model names
-- camelCase for field names
-
-You can adjust the naming by _mapping_ the Prisma model and field names to the existing table and column names in the underlying database using `@@map` and `@map`.
-
-Also note that you can rename [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) to optimize the Prisma Client API that you'll use later to send queries to your database. For example, the `post` field on the `user` model is a _list_, so a better name for this field would be `posts` to indicate that it's plural.
-
-You can further completely remove model that represents the TypeORM migrations table (called `_typeorm_migrations` here) from the Prisma schema.
-
-Here's an adjusted version of the Prisma schema that addresses these points:
-
-```prisma file=prisma/schema.prisma showLineNumbers
-model Category {
- id Int @id @default(autoincrement())
- name String
- postsToCategories PostToCategories[]
-
- @@map("category")
-}
-
-model Post {
- id Int @id @default(autoincrement())
- title String
- content String?
- published Boolean @default(false)
- authorId Int?
- author User? @relation(fields: [authorId], references: [id])
- postsToCategories PostToCategories[]
-
- @@map("post")
-}
-
-model PostToCategories {
- postId Int
- categoryId Int
- category Category @relation(fields: [categoryId], references: [id])
- post Post @relation(fields: [postId], references: [id])
-
- @@id([postId, categoryId])
- @@index([postId], name: "IDX_93b566d522b73cb8bc46f7405b")
- @@index([categoryId], name: "IDX_a5e63f80ca58e7296d5864bd2d")
- @@map("post_categories_category")
-}
-
-model Profile {
- id Int @id @default(autoincrement())
- bio String?
- userId Int? @unique
- user User? @relation(fields: [userId], references: [id])
-
- @@map("profile")
-}
-
-model User {
- id Int @id @default(autoincrement())
- name String?
- email String @unique
- posts Post[]
- profile Profile?
-
- @@map("user")
-}
-```
-
-## Step 3. Install Prisma Client
-
-As a next step, you can install Prisma Client in your project so that you can start replacing the database queries in your project that are currently made with TypeORM:
-
-```terminal
-npm install @prisma/client
-```
-
-## Step 4. Replace your TypeORM queries with Prisma Client
-
-In this section, we'll show a few sample queries that are being migrated from TypeORM to Prisma Client based on the example routes from the sample REST API project. For a comprehensive overview of how the Prisma Client API differs from TypeORM, check out the [API comparison](/orm/more/comparisons/prisma-and-typeorm#api-comparison) page.
-
-First, to set up the `PrismaClient` instance that you'll use to send database queries from the various route handlers. Create a new file named `prisma.ts` in the `src` directory:
-
-```terminal copy
-touch src/prisma.ts
-```
-
-Now, instantiate `PrismaClient` and export it from the file so you can use it in your route handlers later:
-
-```ts copy file=src/prisma.ts showLineNumbers
-import { PrismaClient } from '@prisma/client'
-
-export const prisma = new PrismaClient()
-```
-
-### 4.1. Replacing queries in `GET` requests
-
-The REST API has three routes that accept `GET` requests:
-
-- `/feed`: Return all published posts
-- `/filterPosts?searchString=SEARCH_STRING`: Filter returned posts by `SEARCH_STRING`
-- `/post/:postId`: Returns a specific post
-
-Let's dive into the route handlers that implement these requests.
-
-#### `/feed`
-
-The `/feed` handler is currently implemented as follows:
-
-```ts file=src/controllers/FeedAction.ts showLineNumbers
-import { getManager } from 'typeorm'
-import { Post } from '../entity/Post'
-
-export async function feedAction(req, res) {
- const postRepository = getManager().getRepository(Post)
-
- const publishedPosts = await postRepository.find({
- where: { published: true },
- relations: ['author'],
- })
-
- res.send(publishedPosts)
-}
-```
-
-Note that each returned `Post` object includes the relation to the `author` it's associated with. With TypeORM, including the relation is not type-safe. For example, if there was a typo in the relation that is retrieved, your database query would fail only at _runtime_ – the TypeScript compiler does not provide any safety here.
-
-Here is how the same route is implemented using Prisma Client:
-
-```ts file=src/controllers/FeedAction.ts showLineNumbers
-import { prisma } from '../prisma'
-
-export async function feedAction(req, res) {
- const publishedPosts = await prisma.post.findMany({
- where: { published: true },
- include: { author: true },
- })
-
- res.send(publishedPosts)
-}
-```
-
-Note that the way how Prisma Client includes the `author` relation is absolutely type-safe. The TypeScript compiler would throw an error if you were trying to include a relation that does not exist on the `Post` model.
-
-#### `/filterPosts?searchString=SEARCH_STRING`
-
-The `/filterPosts` handler is currently implemented as follows:
-
-```ts file=src/controllers/FilterPostsActions.ts showLineNumbers
-import { getManager, Like } from 'typeorm'
-import { Post } from '../entity/Post'
-
-export async function filterPostsAction(req, res) {
- const { searchString } = req.query
- const postRepository = getManager().getRepository(Post)
-
- const filteredPosts = await postRepository.find({
- where: [
- { title: Like(`%${searchString}%`) },
- { content: Like(`%${searchString}%`) },
- ],
- })
-
- res.send(filteredPosts)
-}
-```
-
-With Prisma ORM, the route is implemented as follows:
-
-```ts file=src/controllers/FilterPostsActions.ts showLineNumbers
-import { prisma } from '../prisma'
-
-export async function filterPostsAction(req, res) {
- const { searchString } = req.query
-
- const filteredPosts = prisma.post.findMany({
- where: {
- OR: [
- {
- title: { contains: searchString },
- },
- {
- content: { contains: searchString },
- },
- ],
- },
- })
-
- res.send(filteredPosts)
-}
-```
-
-Note that TypeORM by default combines several `where` conditions with an implicit `OR` operator. Prisma ORM on the other hand [combines several `where` conditions with an implicit `AND` operator](/orm/reference/prisma-client-reference#get-all-post-records-where-the-content-field-contains-prisma-and-published-is-false-no-and), so in this case the Prisma Client query needs to make the `OR` explicit.
-
-#### `/post/:postId`
-
-The `/post/:postId` handler is currently implemented as follows:
-
-```ts file=src/controllers/GetPostByIdAction.ts showLineNumbers
-import { getManager } from 'typeorm'
-import { Post } from '../entity/Post'
-
-export async function getPostByIdAction(req, res) {
- const { postId } = req.params
- const postRepository = getManager().getRepository(Post)
-
- const post = await postRepository.findOne(postId)
-
- res.send(post)
-}
-```
-
-With Prisma ORM, the route is implemented as follows:
-
-```ts file=src/controllers/GetPostByIdAction.ts showLineNumbers
-import { prisma } from '../prisma'
-
-export async function getPostByIdAction(req, res) {
- const { postId } = req.params
-
- const post = await prisma.post.findUnique({
- where: { id: postId },
- })
-
- res.send(post)
-}
-```
-
-### 4.2. Replacing queries in `POST` requests
-
-The REST API has three routes that accept `POST` requests:
-
-- `/user`: Creates a new `User` record
-- `/post`: Creates a new `Post` record
-- `/user/:userId/profile`: Creates a new `Profile` record for a `User` record with a given ID
-
-#### `/user`
-
-The `/user` handler is currently implemented as follows:
-
-```ts file=src/controllers/CreateUserAction.ts showLineNumbers
-import { getManager } from 'typeorm'
-import { User } from '../entity/User'
-
-export async function createUserAction(req, res) {
- const { name, email } = req.body
-
- const userRepository = getManager().getRepository(User)
-
- const newUser = new User()
- newUser.name = name
- newUser.email = email
- userRepository.save(newUser)
-
- res.send(newUser)
-}
-```
-
-With Prisma ORM, the route is implemented as follows:
-
-```ts file=src/controllers/CreateUserAction.ts showLineNumbers
-import { prisma } from '../prisma'
-
-export async function createUserAction(req, res) {
- const { name, email } = req.body
-
- const newUser = await prisma.user.create({
- data: {
- name,
- email,
- },
- })
-
- res.send(newUser)
-}
-```
-
-#### `/post`
-
-The `/post` handler is currently implemented as follows:
-
-```ts file=src/controllers/CreateDraftAction.ts
-import { getManager } from 'typeorm'
-import { Post } from '../entity/Post'
-import { User } from '../entity/User'
-
-export async function createDraftAction(req, res) {
- const { title, content, authorEmail } = req.body
-
- const userRepository = getManager().getRepository(User)
- const user = await userRepository.findOne({ email: authorEmail })
-
- const postRepository = getManager().getRepository(Post)
-
- const newPost = new Post()
- newPost.title = title
- newPost.content = content
- newPost.author = user
- postRepository.save(newPost)
-
- res.send(newPost)
-}
-```
-
-With Prisma ORM, the route is implemented as follows:
-
-```ts file=src/controllers/CreateDraftAction.ts showLineNumbers
-import { prisma } from '../prisma'
-
-export async function createDraftAction(req, res) {
- const { title, content, authorEmail } = req.body
-
- const newPost = await prisma.post.create({
- data: {
- title,
- content,
- author: {
- connect: { email: authorEmail },
- },
- },
- })
-
- res.send(newPost)
-}
-```
-
-Note that Prisma Client's nested write here save an initial query where first the `User` record needs to be retrieved by its `email`. That's because, with Prisma Client you can connect records in relations using any unique property.
-
-#### `/user/:userId/profile`
-
-The `/user/:userId/profile` handler is currently implemented as follows:
-
-```ts file=src/controllers/SetBioForUserAction.ts.ts showLineNumbers
-import { getManager } from 'typeorm'
-import { Profile } from '../entity/Profile'
-import { User } from '../entity/User'
-
-export async function setBioForUserAction(req, res) {
- const { userId } = req.params
- const { bio } = req.body
-
- const userRepository = getManager().getRepository(User)
- const user = await userRepository.findOne(userId, {
- relations: ['profile'],
- })
-
- const profileRepository = getManager().getRepository(Profile)
- user.profile.bio = bio
-
- profileRepository.save(user.profile)
-
- res.send(user)
-}
-```
-
-With Prisma ORM, the route is implemented as follows:
-
-```ts file=src/controllers/SetBioForUserAction.ts.ts showLineNumbers
-import { prisma } from '../prisma'
-
-export async function setBioForUserAction(req, res) {
- const { userId } = req.params
- const { bio } = req.body
-
- const user = await prisma.user.update({
- where: { id: userId },
- data: {
- profile: {
- update: {
- bio,
- },
- },
- },
- })
-
- res.send(user)
-}
-```
-
-### 4.3. Replacing queries in `PUT` requests
-
-The REST API has one route that accept a `PUT` request:
-
-- `/addPostToCategory?postId=POST_ID&categoryId=CATEGORY_ID`: Adds the post with `POST_ID` to the category with `CATEGORY_ID`
-
-Let's dive into the route handlers that implement these requests.
-
-#### `/addPostToCategory?postId=POST_ID&categoryId=CATEGORY_ID`
-
-The `/addPostToCategory?postId=POST_ID&categoryId=CATEGORY_ID` handler is currently implemented as follows:
-
-```ts file=src/controllers/AddPostToCategoryAction.ts showLineNumbers
-import { getManager } from 'typeorm'
-import { Post } from '../entity/Post'
-import { Category } from '../entity/Category'
-
-export async function addPostToCategoryAction(req, res) {
- const { postId, categoryId } = req.query
-
- const postRepository = getManager().getRepository(Post)
- const post = await postRepository.findOne(postId, {
- relations: ['categories'],
- })
-
- const categoryRepository = getManager().getRepository(Category)
- const category = await categoryRepository.findOne(categoryId)
-
- post.categories.push(category)
- postRepository.save(post)
-
- res.send(post)
-}
-```
-
-With Prisma ORM, the route is implemented as follows:
-
-```ts file=src/controllers/AddPostToCategoryAction.ts showLineNumbers
-import { prisma } from '../prisma'
-
-export async function addPostToCategoryAction(req, res) {
- const { postId, categoryId } = req.query
-
- const post = await prisma.post.update({
- data: {
- postsToCategories: {
- create: {
- category: {
- connect: { id: categoryId },
- },
- },
- },
- },
- where: {
- id: postId,
- },
- })
-
- res.send(post)
-}
-```
-
-Note that this Prisma Client can be made less verbose by modeling the relation as an [implicit many-to-many relation](#implicit-many-to-many-relations) instead. In that case, the query would look as follows:
-
-```ts file=src/controllers/AddPostToCategoryAction.ts showLineNumbers
-const post = await prisma.post.update({
- data: {
- categories: {
- connect: { id: categoryId },
- },
- },
- where: { id: postId },
-})
-```
-
-## More
-
-### Implicit many-to-many relations
-
-Similar to the `@manyToMany` decorator in TypeORM, Prisma ORM allows you to [model many-to-many relations _implicitly_](/orm/prisma-schema/data-model/relations/many-to-many-relations#implicit-many-to-many-relations). That is, a many-to-many relation where you do not have to manage the [relation table](/orm/prisma-schema/data-model/relations/many-to-many-relations#relation-tables) (also sometimes called JOIN table) _explicitly_ in your schema. Here is an example with TypeORM:
-
-```ts
-import {
- Entity,
- PrimaryGeneratedColumn,
- Column,
- ManyToMany,
- JoinTable,
-} from 'typeorm'
-import { Category } from './Category'
-
-@Entity()
-export class Post {
- @PrimaryGeneratedColumn()
- id: number
-
- @ManyToMany((type) => Category, (category) => category.posts)
- @JoinTable()
- categories: Category[]
-}
-```
-
-```ts
-import { Entity, PrimaryGeneratedColumn, Column, ManyToMany } from 'typeorm'
-import { Post } from './Post'
-
-@Entity()
-export class Category {
- @PrimaryGeneratedColumn()
- id: number
-
- @ManyToMany((type) => Post, (post) => post.categories)
- posts: Post[]
-}
-```
-
-If you generate and run a migration with TypeORM based on these models, TypeORM will automatically create the following relation table for you:
-
-```sql
--- Table Definition ----------------------------------------------
-CREATE TABLE post_categories_category (
- "postId" integer REFERENCES post(id) ON DELETE CASCADE,
- "categoryId" integer REFERENCES category(id) ON DELETE CASCADE,
- CONSTRAINT "PK_91306c0021c4901c1825ef097ce" PRIMARY KEY ("postId", "categoryId")
-);
-
--- Indices -------------------------------------------------------
-CREATE UNIQUE INDEX "PK_91306c0021c4901c1825ef097ce" ON post_categories_category("postId" int4_ops,"categoryId" int4_ops);
-CREATE INDEX "IDX_93b566d522b73cb8bc46f7405b" ON post_categories_category("postId" int4_ops);
-CREATE INDEX "IDX_a5e63f80ca58e7296d5864bd2d" ON post_categories_category("categoryId" int4_ops);
-```
-
-If you introspect the database with Prisma ORM, you'll get the following result in the Prisma schema (note that some relation field names have been adjusted to look friendlier compared to the raw version from introspection):
-
-```prisma file=schema.prisma
-model Category {
- id Int @id @default(autoincrement())
- name String
- postsToCategories PostToCategories[]
-
- @@map("category")
-}
-
-model Post {
- id Int @id @default(autoincrement())
- title String
- content String?
- published Boolean @default(false)
- authorId Int?
- author User? @relation(fields: [authorId], references: [id])
- postsToCategories PostToCategories[]
-
- @@map("post")
-}
-
-model PostToCategories {
- postId Int
- categoryId Int
- category Category @relation(fields: [categoryId], references: [id])
- post Post @relation(fields: [postId], references: [id])
-
- @@id([postId, categoryId])
- @@index([postId], name: "IDX_93b566d522b73cb8bc46f7405b")
- @@index([categoryId], name: "IDX_a5e63f80ca58e7296d5864bd2d")
- @@map("post_categories_category")
-}
-```
-
-In this Prisma schema, the many-to-many relation is modeled _explicitly_ via the relation table `PostToCategories`.
-
-By adhering to the conventions for Prisma ORM relation tables, the relation could look as follows:
-
-```prisma file=schema.prisma showLineNumbers
-model Category {
- id Int @id @default(autoincrement())
- name String
- posts Post[]
-
- @@map("category")
-}
-
-model Post {
- id Int @id @default(autoincrement())
- title String
- content String?
- published Boolean @default(false)
- authorId Int?
- author User? @relation(fields: [authorId], references: [id])
- categories Category[]
-
- @@map("post")
-}
-```
-
-This would also result in a more ergonomic and less verbose Prisma Client API to modify the records in this relation, because you have a direct path from `Post` to `Category` (and the other way around) instead of needing to traverse the `PostToCategories` model first.
-
-
- If your database provider requires tables to have primary keys then you have
- to use explicit syntax, and manually create the join model with a primary key.
- This is because relation tables (JOIN tables) created by Prisma ORM (expressed via `@relation`) for many-to-many relations using implicit syntax do not have primary keys.
-
diff --git a/content/200-orm/800-more/450-migrating-to-prisma/02-migrate-from-sequelize.mdx b/content/200-orm/800-more/450-migrating-to-prisma/02-migrate-from-sequelize.mdx
deleted file mode 100644
index b6e1d22d67..0000000000
--- a/content/200-orm/800-more/450-migrating-to-prisma/02-migrate-from-sequelize.mdx
+++ /dev/null
@@ -1,1280 +0,0 @@
----
-title: 'Migrate from Sequelize'
-metaTitle: 'How to migrate from Sequelize to Prisma ORM'
-metaDescription: 'Learn how to migrate from Sequelize to Prisma ORM'
----
-
-
-
-This guide describes how to migrate from Sequelize to Prisma ORM. It uses an extended version of the [Sequelize Express example](https://github.com/sequelize/express-example) as a [sample project](https://github.com/prisma/migrate-from-sequelize-to-prisma) to demonstrate the migration steps. You can find the example used for this guide on [GitHub](https://github.com/prisma/migrate-from-sequelize-to-prisma).
-
-This migration guide uses PostgreSQL as the example database, but it equally applies to any other relational database that's [supported by Prisma](/orm/reference/supported-databases).
-
-You can learn how Prisma ORM compares to Sequelize on the [Prisma ORM vs Sequelize](/orm/more/comparisons/prisma-and-sequelize) page.
-
-
-
-## Overview of the migration process
-
-Note that the steps for migrating from Sequelize to Prisma ORM are always the same, no matter what kind of application or API layer you're building:
-
-1. Install the Prisma CLI
-1. Introspect your database
-1. Create a baseline migration
-1. Install Prisma Client
-1. Gradually replace your Sequelize queries with Prisma Client
-
-These steps apply, no matter if you're building a REST API (e.g. with Express, koa or NestJS), a GraphQL API (e.g. with Apollo Server, TypeGraphQL or Nexus) or any other kind of application that uses Sequelize for database access.
-
-Prisma ORM lends itself really well for **incremental adoption**. This means, you don't have migrate your entire project from Sequelize to Prisma ORM at once, but rather you can _step-by-step_ move your database queries from Sequelize to Prisma ORM.
-
-## Overview of the sample project
-
-For this guide, we'll use a REST API built with Express as a [sample project](https://github.com/prisma/migrate-from-sequelize-to-prisma) to migrate to Prisma ORM. It has four models/entities:
-
-
-
-
-
-```js
-module.exports = (sequelize, DataTypes) => {
- const User = sequelize.define('User', {
- name: {
- type: DataTypes.STRING,
- },
- email: {
- type: DataTypes.STRING,
- unique: true,
- allowNull: false,
- },
- })
-
- User.associate = (models) => {
- User.hasMany(models.Post, {
- foreignKey: 'authorId',
- as: 'posts',
- })
- User.hasOne(models.Profile, {
- onDelete: 'CASCADE',
- foreignKey: 'userId',
- })
- }
- return User
-}
-```
-
-
-
-
-
-```js
-module.exports = (sequelize, DataTypes) => {
- const Post = sequelize.define('Post', {
- title: {
- type: DataTypes.STRING,
- allowNull: false,
- },
- content: {
- type: DataTypes.STRING,
- },
- published: {
- type: DataTypes.BOOLEAN,
- defaultValue: false,
- },
- })
- Post.associate = (models) => {
- Post.belongsTo(models.User, {
- foreignKey: 'authorId',
- as: 'author',
- })
- Post.belongsToMany(models.Category, {
- through: 'PostCategories',
- as: 'categories',
- })
- }
- return Post
-}
-```
-
-
-
-
-
-```js
-module.exports = (sequelize, DataTypes) => {
- const Profile = sequelize.define('Profile', {
- bio: {
- type: DataTypes.STRING,
- allowNull: false,
- },
- })
- Profile.associate = (models) => {
- Profile.belongsTo(models.User, {
- foreignKey: 'userId',
- as: 'user',
- })
- }
- return Profile
-}
-```
-
-
-
-
-
-```js
-module.exports = (sequelize, DataTypes) => {
- const Category = sequelize.define('Category', {
- name: {
- type: DataTypes.STRING,
- allowNull: false,
- },
- })
- Category.associate = (models) => {
- Category.belongsToMany(models.Post, {
- through: 'PostCategories',
- as: 'posts',
- })
- }
- return Category
-}
-```
-
-
-
-
-
-The models have the following relations:
-
-- 1-1: `User` ↔ `Profile`
-- 1-n: `User` ↔ `Post`
-- m-n: `Post` ↔ `Category`
-
-The corresponding tables have been created using a generated Sequelize migration.
-
-In this guide, the route handlers are located in the `src/controllers` directory. The models are located in the `src/models` directory. From there, they are pulled into a central `src/routes.js` file which is used to set up the required routes in `src/index.js`:
-
-```
-└── blog-sequelize
- ├── package.json
- └──src
- ├── controllers
- │ ├── post.js
- │ └── user.js
- ├── models
- │ ├── Category.js
- │ ├── Post.js
- │ ├── Profile.js
- │ └── User.js
- ├── index.js
- └── routes.js
-```
-
-## Step 1. Install the Prisma CLI
-
-The first step to adopt Prisma ORM is to [install the Prisma CLI](/orm/tools/prisma-cli#installation) in your project:
-
-```terminal copy
-npm install prisma --save-dev
-```
-
-## Step 2. Introspect your database
-
-### 2.1. Set up Prisma ORM
-
-Before you can introspect your database, you need to set up your [Prisma schema](/orm/prisma-schema) and connect Prisma ORM to your database. Run the following command in your terminal to create a basic Prisma schema file:
-
-```terminal copy
-npx prisma init
-```
-
-This command created a new directory called `prisma` with the following files for you:
-
-- `schema.prisma`: Your Prisma schema that specifies your database connection and models
-- `.env`: A [`dotenv`](https://github.com/motdotla/dotenv) to configure your database connection URL as an environment variable
-
-The Prisma schema currently looks as follows:
-
-```prisma file=prisma/schema.prisma showLineNumbers
-// This is your Prisma schema file,
-// learn more about it in the docs: https://pris.ly/d/prisma-schema
-
-datasource db {
- provider = "postgresql"
- url = env("DATABASE_URL")
-}
-
-generator client {
- provider = "prisma-client-js"
-}
-```
-
-:::tip
-
-If you're using VS Code, be sure to install the [Prisma VS Code extension](https://marketplace.visualstudio.com/items?itemName=Prisma.prisma) for syntax highlighting, formatting, auto-completion and a lot more cool features.
-
-:::
-
-### 2.2. Connect your database
-
-If you're not using PostgreSQL, you need to adjust the `provider` field on the `datasource` block to the database you currently use:
-
-
-
-
-
-```prisma
-datasource db {
- provider = "postgresql"
- url = env("DATABASE_URL")
-}
-```
-
-
-
-
-
-```prisma
-datasource db {
- provider = "mysql"
- url = env("DATABASE_URL")
-}
-```
-
-
-
-
-
-```prisma
-datasource db {
- provider = "sqlserver"
- url = env("DATABASE_URL")
-}
-```
-
-
-
-
-
-```prisma
-datasource db {
- provider = "sqlite"
- url = env("DATABASE_URL")
-}
-```
-
-
-
-
-
-Once that's done, you can configure your [database connection URL](/orm/reference/connection-urls) in the `.env` file. Here's how the database connection from Sequelize maps to the connection URL format used by Prisma ORM:
-
-
-
-
-
-
-Assume you have the following database connection details in `src/models/index.js`:
-
-
-```js file=src/models/index.js
-const sequelize = new Sequelize('blog-sequelize', 'alice', 'myPassword42', {
- host: 'localhost',
- dialect: 'postgres',
-})
-```
-
-The respective connection URL would look as follows in Prisma ORM:
-
-
-```env file=.env
-DATABASE_URL="postgresql://alice:myPassword42@localhost:5432/blog-sequelize"
-```
-
-
-Note that you can optionally configure the PostgreSQL [schema](https://www.postgresql.org/docs/9.1/ddl-schemas.html) by appending the `schema` argument to the connection URL:
-
-
-```env file=.env
-DATABASE_URL="postgresql://alice:myPassword42@localhost:5432/blog-sequelize?schema=myschema"
-```
-
-
-If not provided, the default schema called `public` is being used.
-
-
-
-
-
-
-
-Assume you have the following database connection details in `src/models/index.js`:
-
-
-```js file=src/models/index.js
-const sequelize = new Sequelize('blog-sequelize', 'alice', 'myPassword42', {
- host: 'localhost',
- dialect: 'postgres',
-})
-```
-
-
-The respective connection URL would look as follows in Prisma:
-
-
-```env file=.env
-DATABASE_URL="mysql://alice:myPassword42@localhost:3306/blog-sequelize"
-```
-
-
-
-
-
-
-Assume you have the following database connection details in `src/models/index.js`:
-
-
-```js file=src/models/index.js
-const sequelize = new Sequelize('blog-sequelize', 'alice', 'myPassword42', {
- host: 'localhost',
- dialect: 'mssql',
-})
-```
-
-
-The respective connection URL would look as follows in Prisma:
-
-
-```env file=.env
-DATABASE_URL="sqlserver://localhost:1433;database=blog-sequelize;user=alice;password=myPassword42;trustServerCertificate=true"
-```
-
-
-
-
-
-
-Assume you have the following database connection details in `src/models/index.js`:
-
-
-```js file=src/models/index.js
-const sequelize = new Sequelize({
- dialect: 'sqlite',
- storage: '../../blog-sequelize.sqlite',
-})
-```
-
-
-The respective connection URL would look as follows in Prisma:
-
-
-```env file=.env
-DATABASE_URL="file:./blog-sequelize.db"
-```
-
-
-
-
-
-### 2.3. Introspect your database using Prisma ORM
-
-With your connection URL in place, you can [introspect](/orm/prisma-schema/introspection) your database to generate your Prisma models:
-
-```terminal copy
-npx prisma db pull
-```
-
-This creates the following Prisma models:
-
-```prisma file=prisma/schema.prisma showLineNumbers
-model Categories {
- id Int @id @default(autoincrement())
- name String
- createdAt DateTime
- updatedAt DateTime
- PostCategories PostCategories[]
-}
-
-model PostCategories {
- createdAt DateTime
- updatedAt DateTime
- CategoryId Int
- PostId Int
- Categories Categories @relation(fields: [CategoryId], references: [id])
- Posts Posts @relation(fields: [PostId], references: [id])
-
- @@id([CategoryId, PostId])
-}
-
-model Posts {
- id Int @id @default(autoincrement())
- title String
- content String?
- published Boolean? @default(false)
- createdAt DateTime
- updatedAt DateTime
- authorId Int?
- Users Users? @relation(fields: [authorId], references: [id])
- PostCategories PostCategories[]
-}
-
-model Profiles {
- id Int @id @default(autoincrement())
- bio String
- createdAt DateTime
- updatedAt DateTime
- userId Int? @unique
- Users Users? @relation(fields: [userId], references: [id])
-}
-
-model SequelizeMeta {
- name String @id
-}
-
-model Users {
- id Int @id @default(autoincrement())
- name String?
- email String @unique
- createdAt DateTime
- updatedAt DateTime
- Posts Posts[]
- Profiles Profiles?
-}
-```
-
-### 2.4. Create a baseline migration
-
-To continue using Prisma Migrate to evolve your database schema, you will need to [baseline your database](/orm/prisma-migrate/getting-started).
-
-First, create a `migrations` directory and add a directory inside with your preferred name for the migration. In this example, we will use `0_init` as the migration name:
-
-```terminal
-mkdir -p prisma/migrations/0_init
-```
-
-Next, generate the migration file with `prisma migrate diff`. Use the following arguments:
-
-- `--from-empty`: assumes the data model you're migrating from is empty
-- `--to-schema-datamodel`: the current database state using the URL in the `datasource` block
-- `--script`: output a SQL script
-
-```terminal wrap
-npx prisma migrate diff --from-empty --to-schema-datamodel prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql
-```
-
-Review the generated migration to ensure everything is correct.
-
-Next, mark the migration as applied using `prisma migrate resolve` with the `--applied` argument.
-
-```terminal
-npx prisma migrate resolve --applied 0_init
-```
-
-The command will mark `0_init` as applied by adding it to the `_prisma_migrations` table.
-
-You now have a baseline for your current database schema. To make further changes to your database schema, you can update your Prisma schema and use `prisma migrate dev` to apply the changes to your database.
-
-### 2.5. Adjust `createdAt` and `updatedAt` fields
-
-The generated Prisma models represent your database tables and are the foundation for your programmatic Prisma Client API which allows you to send queries to your database.
-You'll adjust the `createdAt` and `updatedAt` fields in our models. Sequelize doesn't add the `DEFAULT` constraint to `createdAt` when creating the tables in the database.
-Therefore, you'll add `@default(now())` and `@updatedAt` attributes to the `createdAt` and `updatedAt` columns respectively.
-To learn more how Prisma ORM does this, you can read more [`@default(now())`](/orm/reference/prisma-schema-reference#now) and [`@updatedAt`](/orm/reference/prisma-schema-reference#updatedat) here.
-Our updated schema will be as follows:
-
-```prisma file=prisma/schema.prisma showLineNumbers
-model Categories {
- id Int @id @default(autoincrement())
- name String
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
- PostCategories PostCategories[]
-}
-
-model PostCategories {
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
- CategoryId Int
- PostId Int
- Categories Categories @relation(fields: [CategoryId], references: [id])
- Posts Posts @relation(fields: [PostId], references: [id])
-
- @@id([CategoryId, PostId])
-}
-
-model Posts {
- id Int @id @default(autoincrement())
- title String
- content String?
- published Boolean? @default(false)
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
- authorId Int?
- Users Users? @relation(fields: [authorId], references: [id])
- PostCategories PostCategories[]
-}
-
-model Profiles {
- id Int @id @default(autoincrement())
- bio String
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
- userId Int? @unique
- Users Users? @relation(fields: [userId], references: [id])
-}
-
-model SequelizeMeta {
- name String @id
-}
-
-model Users {
- id Int @id @default(autoincrement())
- name String?
- email String @unique
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
- Posts Posts[]
- Profiles Profiles?
-}
-```
-
-### 2.6. Adjust the Prisma schema (optional)
-
-The models that were generated via introspection currently _exactly_ map to your database tables. In this section, you'll learn how you can adjust the naming of the Prisma models to adhere to [Prisma ORM's naming conventions](/orm/reference/prisma-schema-reference#naming-conventions).
-
-All of these adjustment are entirely optional and you are free to skip to the next step already if you don't want to adjust anything for now. You can go back and make the adjustments at any later point.
-
-As opposed to the current snake_case notation of Prisma models, Prisma ORM's naming conventions are:
-
-- PascalCase for model names
-- camelCase for field names
-
-You can adjust the naming by _mapping_ the Prisma model and field names to the existing table and column names in the underlying database using `@@map` and `@map`.
-
-Also note that you can rename [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) to optimize the Prisma Client API that you'll use later to send queries to your database. For example, although we are singularizing the `Posts` model name to `Post`, the `posts` field on the `user` model is a _list_, so it makes sense to keep that named `posts` to indicate that it's plural.
-
-Sequelize generates a `SequelizeMeta` model that is used internally by the library that is not needed. Therefore, you'll manually delete it from the schema.
-
-Here's an adjusted version of the Prisma schema that addresses these points:
-
-```prisma file=prisma/schema.prisma showLineNumbers
-generator client {
- provider = "prisma-client-js"
-}
-
-datasource db {
- provider = "postgresql"
- url = env("DATABASE_URL")
-}
-
-model Category {
- id Int @id @default(autoincrement())
- name String
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
- postCategories PostToCategories[]
-
- @@map("Categories")
-}
-
-model PostToCategories {
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
- categoryId Int
- postId Int
- category Category @relation(fields: [categoryId], references: [id])
- post Post @relation(fields: [postId], references: [id])
-
- @@id([categoryId, postId])
- @@map("PostCategories")
-}
-
-model Post {
- id Int @id @default(autoincrement())
- title String
- content String?
- published Boolean? @default(false)
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
- authorId Int?
- author User? @relation(fields: [authorId], references: [id])
- postToCategories PostToCategories[]
-
- @@map("Posts")
-}
-
-model Profile {
- id Int @id @default(autoincrement())
- bio String
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
- userId Int? @unique
- user User? @relation(fields: [userId], references: [id])
-
- @@map("Profiles")
-}
-
-model User {
- id Int @id @default(autoincrement())
- name String?
- email String @unique
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
- posts Post[]
- profile Profile?
-
- @@map("Users")
-}
-```
-
-## Step 3. Install Prisma Client
-
-As a next step, you can install Prisma Client in your project so that you can start replacing the database queries in your project that are currently made with Sequelize:
-
-```terminal
-npm install @prisma/client
-```
-
-## Step 4. Replace your Sequelize queries with Prisma Client
-
-In this section, we'll show a few sample queries that are being migrated from Sequelize to Prisma Client based on the example routes from the sample REST API project. For a comprehensive overview of how the Prisma Client API differs from Sequelize, check out the [API comparison](/orm/more/comparisons/prisma-and-sequelize#api-comparison) page.
-
-First, to set up the `PrismaClient` instance that you'll use to send database queries from the various route handlers. Create a new file named `prisma.js` in the `src` directory:
-
-```terminal copy
-touch src/prisma.js
-```
-
-Now, instantiate `PrismaClient` and export it from the file so you can use it in your route handlers later:
-
-```js copy file=src/prisma.js showLineNumbers
-const { PrismaClient } = require('@prisma/client')
-
-const prisma = new PrismaClient()
-
-module.exports = prisma
-```
-
-The imports in our controller files are as follows:
-
-```js file=src/controllers/post.js showLineNumbers
-const { Post, User, Category } = require('../models')
-const { Op } = require('sequelize')
-```
-
-```js file=src/controllers/user.js showLineNumbers
-const { User } = require('../models')
-```
-
-You'll update the controller imports as you migrate from Sequelize to Prisma:
-
-```js file=src/controllers/post.js showLineNumbers
-const prisma = require('../prisma')
-```
-
-```js file=src/controllers/user.js showLineNumbers
-const prisma = require('../prisma')
-```
-
-### 4.1. Replacing queries in `GET` requests
-
-The REST API has four routes that accept `GET` requests:
-
-- `/feed`: Return all published posts
-- `/filterPosts?searchString=SEARCH_STRING`: Filter returned posts by `SEARCH_STRING`
-- `/post/:postId`: Returns a specific post
-- `/authors`: Returns a list of authors
-
-Let's dive into the route handlers that implement these requests.
-
-#### `/feed`
-
-The `/feed` handler is currently implemented as follows:
-
-```js file=src/controllers/post.js showLineNumbers
-const feed = async (req, res) => {
- try {
- const feed = await Post.findAll({
- where: { published: true },
- include: ['author', 'categories'],
- })
- return res.json(feed)
- } catch (error) {
- return res.status(500).json(error)
- }
-}
-```
-
-Note that each returned `Post` object includes the relation to the `author` and `category` it's associated with. With Sequelize, including the relation is not type-safe. For example, if there was a typo in the relation that is retrieved, your database query would fail only at _runtime_ – the JavaScript compiler does not provide any safety here.
-
-Here is how the same route is implemented using Prisma Client:
-
-```js file=src/controllers/post.js
-const feed = async (req, res) => {
- try {
- const feed = await prisma.post.findMany({
- where: { published: true },
- include: { author: true, postToCategories: true },
- })
- return res.json(feed)
- } catch (error) {
- return res.status(500).json(error)
- }
-}
-```
-
-Note that the way how Prisma Client includes the `author` relation is absolutely type-safe. The JavaScript compiler would throw an error if you were trying to include a relation that does not exist on the `Post` model.
-
-#### `/filterPosts?searchString=SEARCH_STRING`
-
-The `/filterPosts` handler is currently implemented as follows:
-
-```js file=src/controllers/post.js showLineNumbers
-const filterPosts = async (req, res) => {
- const { searchString } = req.query
-
- try {
- const filteredPosts = await Post.findAll({
- where: {
- [Op.or]: [
- {
- title: {
- [Op.like]: `%${searchString}%`,
- },
- },
- {
- content: {
- [Op.like]: `%${searchString}%`,
- },
- },
- ],
- },
- include: 'author',
- })
-
- res.json(filteredPosts)
- } catch (error) {
- return res.status(500).json(error)
- }
-}
-```
-
-With Prisma ORM, the route is implemented as follows:
-
-```js file=src/controllers/post.js showLineNumbers
-const filterPosts = async (req, res) => {
- const { searchString } = req.query
-
- try {
- const filteredPosts = prisma.post.findMany({
- where: {
- OR: [
- {
- title: { contains: searchString },
- },
- {
- content: { contains: searchString },
- },
- ],
- },
- })
-
- res.json(filteredPosts)
- } catch (error) {
- return res.status(500).json(error)
- }
-}
-```
-
-Note that Sequelize provides [Operator symbols](https://sequelize.org/docs/v6/core-concepts/model-querying-basics/#operators) - `Op` - to be used when querying data. Prisma ORM on the other hand [combines several `where` conditions with an implicit `AND` operator](/orm/reference/prisma-client-reference#get-all-post-records-where-the-content-field-contains-prisma-and-published-is-false-no-and), so in this case the Prisma Client query needs to make the `OR` explicit.
-
-#### `/post/:postId`
-
-The `/post/:postId` handler is currently implemented as follows:
-
-```js file=src/controllers/post.js showLineNumbers
-const getPostById = async (req, res) => {
- const { postId } = req.params
-
- try {
- const post = await Post.findOne({
- where: { id: postId },
- include: 'author',
- })
-
- return res.json(post)
- } catch (error) {
- return res.status(500).json(error)
- }
-}
-```
-
-With Prisma ORM, the route is implemented as follows:
-
-```js file=src/controllers/post.js showLineNumbers
-const getPostById = async (req, res) => {
- const { postId } = req.params
-
- try {
- const post = await prisma.post.findUnique({
- where: { id: Number(postId) },
- include: { author: true },
- })
-
- return res.json(post)
- } catch (error) {
- return res.status(500).json(error)
- }
-}
-```
-
-### 4.2. Replacing queries in `POST` requests
-
-The REST API has three routes that accept `POST` requests:
-
-- `/user`: Creates a new `User` record
-- `/post`: Creates a new `User` record
-- `/user/:userId/profile`: Creates a new `Profile` record for a `User` record with a given ID
-
-#### `/user`
-
-The `/user` handler is currently implemented as follows:
-
-```js file=src/controllers/user.js
-const createUser = async (req, res) => {
- const { name, email } = req.body
-
- try {
- const user = await User.create({
- name,
- email,
- })
-
- return res.json(user)
- } catch (error) {
- return res.status(500).json(error)
- }
-}
-```
-
-With Prisma ORM, the route is implemented as follows:
-
-```js file=src/controllers/user.js
-const createUser = async (req, res) => {
- const { name, email } = req.body
-
- try {
- const user = await prisma.user.create({
- data: {
- name,
- email,
- },
- })
-
- return res.json(user)
- } catch (error) {
- return res.status(500).json(error)
- }
-}
-```
-
-#### `/post`
-
-The `/post` handler is currently implemented as follows:
-
-```js file=src/controllers/post.js showLineNumbers
-const createDraft = async (req, res) => {
- const { title, content, authorEmail } = req.body
-
- try {
- const user = await User.findOne({ email: authorEmail })
-
- const draft = await Post.create({
- title,
- content,
- authorId: user.id,
- })
-
- res.json(draft)
- } catch (error) {
- return res.status(500).json(error)
- }
-}
-```
-
-With Prisma ORM, the route is implemented as follows:
-
-```js file=src/controllers/post.js showLineNumbers
-const createDraft = async (req, res) => {
- const { title, content, authorEmail } = req.body
-
- try {
- const draft = await prisma.post.create({
- data: {
- title,
- content,
- author: {
- connect: { email: authorEmail },
- },
- },
- })
-
- res.json(draft)
- } catch (error) {
- return res.status(500).json(error)
- }
-}
-```
-
-Note that Prisma Client's nested write here save an initial query where first the `User` record needs to be retrieved by its `email`. That's because, with Prisma Client you can connect records in relations using any unique property.
-
-#### `/user/:userId/profile`
-
-The `/user/:userId/profile` handler is currently implemented as follows:
-
-```js file=src/controllers/user.js
-const setUserBio = async (req, res) => {
- const { userId } = req.params
- const { bio } = req.body
-
- try {
- const user = await User.findOne({
- where: {
- id: Number(userId),
- },
- })
-
- const updatedUser = await user.createProfile({ bio })
-
- return res.json(updatedUser)
- } catch (error) {
- return res.status(500).json(error)
- }
-}
-```
-
-With Prisma ORM, the route is implemented as follows:
-
-```js file=src/controllers/user.js
-const setUserBio = async (req, res) => {
- const { userId } = req.params
- const { bio } = req.body
-
- try {
- const user = await prisma.user.update({
- where: { id: Number(userId) },
- data: {
- profile: {
- create: { bio },
- },
- },
- })
-
- return res.json(user)
- } catch (error) {
- return res.status(500).json(error)
- }
-}
-```
-
-### 4.3. Replacing queries in `PUT` requests
-
-The REST API has one route that accept a `PUT` request:
-
-- `/addPostToCategory?postId=POST_ID&categoryId=CATEGORY_ID`: Adds the post with `POST_ID` to the category with `CATEGORY_ID`
-
-Let's dive into the route handlers that implement these requests.
-
-#### `/addPostToCategory?postId=POST_ID&categoryId=CATEGORY_ID`
-
-The `/addPostToCategory?postId=POST_ID&categoryId=CATEGORY_ID` handler is currently implemented as follows:
-
-```js file=src/controllers/post.js showLineNumbers
-const addPostToCategory = async (req, res) => {
- const { postId, categoryId } = req.query
-
- try {
- const post = await Post.findOne({
- where: { id: postId },
- })
-
- const category = await Category.findOne({
- where: { id: categoryId },
- })
-
- const updatedPost = await post.addCategory(category)
-
- return res.json(updatedPost)
- } catch (error) {
- return res.status(500).json(error)
- }
-}
-```
-
-With Prisma ORM, the route is implemented as follows:
-
-```js file=src/controllers/post.js showLineNumbers
-const addPostToCategory = async (req, res) => {
- const { postId, categoryId } = req.query
-
- try {
- const post = await prisma.post.update({
- data: {
- postToCategories: {
- create: {
- categories: {
- connect: { id: Number(categoryId) },
- },
- },
- },
- },
- where: {
- id: Number(postId),
- },
- })
-
- return res.json(post)
- } catch (error) {
- return res.status(500).json(error)
- }
-}
-```
-
-Note that this Prisma Client can be made less verbose by modeling the relation as an [implicit many-to-many relation](#implicit-many-to-many-relations) instead. In that case, the query would look as follows:
-
-```js file=src/controllers/posts.js showLineNumbers
-const post = await prisma.post.update({
- data: {
- category: {
- connect: { id: categoryId },
- },
- },
- where: { id: postId },
-})
-```
-
-## More
-
-### Primary key column
-
-By default, Sequelize defines a `primaryKey` and used `id` with the autoby default if not defined. This is optional.
-If you would like to set your own primary key, you can use the `primaryKey: true` and define your preferred data type in your field of choice:
-
-```js
-// changing the primary key column
-module.exports = (sequelize, DataTypes) => {
- const Post = sequelize.define('Post', {
- postId: {
- type: DataTypes.INTEGER,
- primaryKey: true,
- },
- })
- return Post
-}
-
-// changing the id DataType
-module.exports = (sequelize, DataTypes) => {
- const Post = sequelize.define('Post', {
- id: {
- type: DataTypes.UUID, // alternative: DataTypes.STRING
- primaryKey: true,
- },
- })
- return Post
-}
-```
-
-### Table name inference
-
-Sequelize infers table names from the model name. When the name of a table isn't provided Sequelize automatically pluralizes the model name and uses that as the table name using a library called [inflection](https://www.npmjs.com/package/inflection).
-Prisma ORM on the other hand maps the model name to the table name in your database [modelling your data](/orm/prisma-schema/data-model/models).
-If you wish to change this default behaviour in Sequelize, you can either enforce the table name to be equal to the model name or provide the table name directly:
-
-```js
-// enforcing table name to be equal to model name
-module.exports = (sequelize, DataTypes) => {
- const Post = sequelize.define(
- 'Post',
- {
- // ... attributes
- },
- {
- freezeTableName: true,
- }
- )
- return Post
-}
-```
-
-```js
-// providing the table name directly
-module.exports = (sequelize, DataTypes) => {
- const Post = sequelize.define(
- 'Post',
- {
- // ... attributes
- },
- {
- tableName: 'Post',
- }
- )
- return Post
-}
-```
-
-### Timestamps
-
-Sequelize automatically adds the fields `createdAt` and `updatedAt` to every model using the data type `DataTypes.DATE`, by default. You can disable this for a model with the `timestamps: false` option:
-
-```js
-sequelize.define(
- 'User',
- {
- // ... (attributes)
- },
- {
- timestamps: false,
- }
-)
-```
-
-Prisma ORM offers you the flexibility to define these fields in your model. You add the `createdAt` and [`updatedAt`](/orm/reference/prisma-schema-reference#updatedat) fields by defining them explicitly in your model.
-To set the `createdAt` field in your model, add the `default(now())` attribute to the column. In order to set the `updatedAt` column, update your model by adding the `@updatedAt` attribute to the column.
-
-```prisma
-model User {
- id Int @id @default(autoincrement())
- name String?
- email String @unique
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
-}
-```
-
-### Implicit many-to-many relations
-
-Similar to the `belongsToMany()` association method in Sequelize, Prisma ORM allows you to [model many-to-many relations _implicitly_](/orm/prisma-schema/data-model/relations/many-to-many-relations#implicit-many-to-many-relations). That is, a many-to-many relation where you do not have to manage the [relation table](/orm/prisma-schema/data-model/relations/many-to-many-relations#relation-tables) (also sometimes called JOIN table) _explicitly_ in your schema. Here is an example with Sequelize:
-
-```js
-module.exports = (sequelize, DataTypes) => {
- const Post = sequelize.define('Post', {
- title: {
- type: DataTypes.STRING,
- allowNull: false,
- },
- content: {
- type: DataTypes.STRING,
- },
- published: {
- type: DataTypes.BOOLEAN,
- defaultValue: false,
- },
- })
- Post.associate = (models) => {
- Post.belongsTo(models.User, {
- foreignKey: 'authorId',
- as: 'author',
- })
- Post.belongsToMany(models.Category, {
- through: 'PostCategories',
- as: 'categories',
- })
- }
- return Post
-}
-```
-
-```js
-module.exports = (sequelize, DataTypes) => {
- const Category = sequelize.define('Category', {
- name: {
- type: DataTypes.STRING,
- allowNull: false,
- },
- })
- Category.associate = (models) => {
- Category.belongsToMany(models.Post, {
- through: 'PostCategories',
- as: 'posts',
- })
- }
- return Category
-}
-```
-
-When you start your application, Sequelize will create the the tables for you - based on these models:
-
-```sql
-Executing (default): CREATE TABLE IF NOT EXISTS "PostCategories"
-("createdAt" TIMESTAMP WITH TIME ZONE NOT NULL, "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL,
-"CategoryId" INTEGER REFERENCES "Categories" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
-"PostId" INTEGER REFERENCES "Posts" ("id") ON DELETE CASCADE ON UPDATE CASCADE, PRIMARY KEY ("CategoryId","PostId"));
-```
-
-If you introspect the database with Prisma ORM, you'll get the following result in the Prisma schema (note that some relation field names have been adjusted to look friendlier compared to the raw version from introspection):
-
-```prisma
-model Categories {
- id Int @id @default(autoincrement())
- name String
- createdAt DateTime
- updatedAt DateTime
- PostCategories PostCategories[]
-
- @@map("category")
-}
-
-model PostCategories {
- createdAt DateTime
- updatedAt DateTime
- CategoryId Int
- PostId Int
- Categories Categories @relation(fields: [CategoryId], references: [id])
- Posts Posts @relation(fields: [PostId], references: [id])
-
- @@id([CategoryId, PostId])
- @@map("PostCategories")
-}
-
-model Posts {
- id Int @id @default(autoincrement())
- title String
- content String?
- published Boolean? @default(false)
- createdAt DateTime
- updatedAt DateTime
- authorId Int?
- Users Users? @relation(fields: [authorId], references: [id])
- PostCategories PostCategories[]
-
- @@map("post")
-}
-```
-
-In this Prisma schema, the many-to-many relation is modeled explicitly via the relation table `PostCategories`
-
-By adhering to the conventions for Prisma relation tables, the relation could look as follows:
-
-```prisma
-model Categories {
- id Int @id @default(autoincrement())
- name String
- posts Posts[]
-
- @@map("category")
-}
-
-model Posts {
- id Int @id @default(autoincrement())
- title String
- content String?
- published Boolean @default(false)
- authorId Int?
- author User? @relation(fields: [authorId], references: [id])
- categories Categories[]
-
- @@map("post")
-}
-```
-
-This would also result in a more ergonomic and less verbose Prisma Client API to modify the records in this relation, because you have a direct path from `Post` to `Category` (and the other way around) instead of needing to traverse the `PostCategories` model first.
diff --git a/content/200-orm/800-more/450-migrating-to-prisma/03-migrate-from-mongoose.mdx b/content/200-orm/800-more/450-migrating-to-prisma/03-migrate-from-mongoose.mdx
deleted file mode 100644
index bf46fa71fc..0000000000
--- a/content/200-orm/800-more/450-migrating-to-prisma/03-migrate-from-mongoose.mdx
+++ /dev/null
@@ -1,1082 +0,0 @@
----
-title: 'Migrate from Mongoose'
-metaTitle: 'How to migrate from Mongoose to Prisma ORM'
-metaDescription: 'Learn how to migrate from Mongoose to Prisma ORM'
----
-
-
-
-This guide describes how to migrate from Mongoose to Prisma ORM. It uses an extended version of the [Mongoose Express example](https://github.com/Automattic/mongoose/tree/master/examples/express) as a [sample project](https://github.com/prisma/migrate-from-mongoose-to-prisma) to demonstrate the migration steps. You can find the example used for this guide on [GitHub](https://github.com/prisma/migrate-from-mongoose-to-prisma).
-
-You can learn how Prisma ORM compares to Mongoose on the [Prisma ORM vs Mongoose](/orm/more/comparisons/prisma-and-mongoose) page.
-
-
-
-## Overview of the migration process
-
-Note that the steps for migrating from Mongoose to Prisma ORM are always the same, no matter what kind of application or API layer you're building:
-
-1. [Install the Prisma CLI](/orm/tools/prisma-cli#installation)
-1. [Introspect your database](/orm/prisma-schema/introspection)
-1. [Install and generate Prisma Client](/orm/prisma-client/setup-and-configuration/generating-prisma-client)
-1. Gradually replace your Mongoose queries with Prisma Client
-
-These steps apply whether you're building a REST API (e.g. with Express, koa or NestJS), a GraphQL API (e.g. with Apollo Server, TypeGraphQL or Nexus) or any other kind of application that uses Mongoose for database access.
-
-Prisma ORM lends itself really well for **incremental adoption**. This means, you don't have to migrate your entire project from Mongoose to Prisma ORM at once, but rather you can _step-by-step_ move your database queries from Mongoose to Prisma ORM.
-
-## Overview of the sample project
-
-For this guide, we'll use a REST API built with Express as a [sample project](https://github.com/prisma/migrate-from-mongoose-to-prisma) to migrate to Prisma ORM. It has three documents and one sub-document (embedded document):
-
-
-
-
-
-```js
-const mongoose = require('mongoose')
-
-const Schema = mongoose.Schema
-
-const PostSchema = new Schema({
- title: String,
- content: String,
- published: {
- type: Boolean,
- default: false,
- },
- author: {
- type: Schema.Types.ObjectId,
- ref: 'author',
- required: true,
- },
- categories: [
- {
- type: Schema.Types.ObjectId,
- ref: 'Category',
- },
- ],
-})
-
-module.exports = mongoose.model('Post', PostSchema)
-```
-
-
-
-
-
-```js
-const mongoose = require('mongoose')
-
-const Schema = mongoose.Schema
-
-const ProfileSchema = new Schema(
- {
- bio: String,
- },
- {
- _id: false,
- }
-)
-
-const UserSchema = new Schema({
- name: String,
- email: {
- type: String,
- unique: true,
- },
- profile: {
- type: ProfileSchema,
- default: () => ({}),
- },
-})
-
-module.exports = mongoose.model('User', UserSchema)
-```
-
-
-
-
-
-```js
-const mongoose = require('mongoose')
-
-const Schema = mongoose.Schema
-
-const CategorySchema = new Schema({
- name: {
- type: String,
- required: true,
- },
-})
-
-module.exports = mongoose.model('Category', CategorySchema)
-```
-
-
-
-
-
-The models/documents have the following types of relationships:
-
-- 1-n: `User` ↔ `Post`
-- m-n: `Post` ↔ `Category`
-- Sub-document/ Embedded document: `User` ↔ `Profile`
-
-In the example used in this guide, the route handlers are located in the `src/controllers` directory. The models are located in the `src/models` directory. From there, the models are pulled into a central `src/routes.js` file, which is used to define the required routes in `src/index.js`:
-
-```copy=false
-└── blog-mongoose
- ├── package.json
- └──src
- ├── controllers
- │ ├── post.js
- │ └── user.js
- ├── models
- │ ├── category.js
- │ ├── post.js
- │ └── user.js
- ├── index.js
- ├── routes.js
- └── seed.js
-```
-
-The example repository contains a `seed` script inside the `package.json` file.
-
-Run `npm run seed` to populate your database with the sample data in the `./src/seed.js` file.
-
-## Step 1. Install the Prisma CLI
-
-The first step to adopt Prisma ORM is to [install the Prisma CLI](/orm/tools/prisma-cli#installation) in your project:
-
-```terminal copy
-npm install prisma --save-dev
-```
-
-## Step 2. Introspect your database
-
-Introspection is a process of inspecting the structure of a database, used in Prisma ORM to generate a [data model](/orm/prisma-schema/data-model/models) in your [Prisma schema](/orm/prisma-schema).
-
-### 2.1. Set up Prisma
-
-Before you can introspect your database, you need to set up your [Prisma schema](/orm/prisma-schema) and connect Prisma ORM to your database. Run the following command in your terminal to create a basic Prisma schema file:
-
-```terminal copy
-npx prisma init --datasource-provider mongodb
-```
-
-This command creates:
-
-- A new directory called `prisma` that contains a `schema.prisma` file; your Prisma schema specifies your database connection and models
-- `.env`: A [`dotenv`](https://github.com/motdotla/dotenv) file at the root of your project (if it doesn't already exist), used to configure your database connection URL as an environment variable
-
-The Prisma schema currently looks as follows:
-
-```prisma file=prisma/schema.prisma showLineNumbers
-// This is your Prisma schema file,
-// learn more about it in the docs: https://pris.ly/d/prisma-schema
-
-datasource db {
- provider = "mongodb"
- url = env("DATABASE_URL")
-}
-
-generator client {
- provider = "prisma-client-js"
-}
-```
-
-
-:::tip
-
-For an optimal development experience when working with Prisma ORM, refer to [editor setup](/orm/more/development-environment/editor-setup) to learn about syntax highlighting, formatting, auto-completion, and many more cool features.
-
-:::
-
-### 2.2. Connect your database
-
-Configure your [database connection URL](/orm/reference/connection-urls#mongodb) in the `.env` file.
-
-The format of the connection URL that Mongoose uses is similar to the one Prisma ORM uses.
-
-```bash file=.env
-DATABASE_URL="mongodb://alice:myPassword43@localhost:27017/blog-mongoose"
-```
-
-Refer to the [MongoDB connection URL specification](https://www.mongodb.com/docs/manual/reference/connection-string/) for further details.
-
-### 2.3. Run Prisma ORM's introspection
-
-With your connection URL in place, you can [introspect](/orm/prisma-schema/introspection) your database to generate your Prisma models:
-
-> **Note**: MongoDB is a _schemaless_ database. To incrementally adopt Prisma ORM in your project, ensure your database is populated with sample data. Prisma ORM introspects a MongoDB schema by sampling data stored and inferring the schema from the data in the database.
-
-```terminal copy
-npx prisma db pull
-```
-
-This creates the following Prisma models:
-
-```prisma file=prisma/schema.prisma showLineNumbers
-type UsersProfile {
- bio String
-}
-
-model categories {
- id String @id @default(auto()) @map("_id") @db.ObjectId
- v Int @map("__v")
- name String
-}
-
-model posts {
- id String @id @default(auto()) @map("_id") @db.ObjectId
- v Int @map("__v")
- author String @db.ObjectId
- categories String[] @db.ObjectId
- content String
- published Boolean
- title String
-}
-
-model users {
- id String @id @default(auto()) @map("_id") @db.ObjectId
- v Int @map("__v")
- email String @unique(map: "email_1")
- name String
- profile UsersProfile?
-}
-```
-
-The generated Prisma models represent the MongoDB collections and are the foundation of your programmatic Prisma Client API which allows you to send queries to your database.
-
-### 2.4. Update the relations
-
-MongoDB doesn't support relations between different collections. However, you can create references between documents using the [`ObjectId`](/orm/overview/databases/mongodb#using-objectid) field type or from one document to many using an array of `ObjectIds` in the collection. The reference will store id(s) of the related document(s). You can use the `populate()` method that Mongoose provides to populate the reference with the data of the related document.
-
-Update the 1-n relationship between `Post` \<-> `User` as follows:
-
-- Rename the existing `author` reference in the `posts` model to `authorId` and add the `@map("author")` attribute
-- Add the `author` relation field in the `posts` model and it's `@relation` attribute specifying the `fields` and `references`
-- Add the `posts` relation in the `users` model
-
-
-
-
-
-```prisma
-type UsersProfile {
- bio String
-}
-
-model categories {
- id String @id @default(auto()) @map("_id") @db.ObjectId
- v Int @map("__v")
- name String
-}
-
-model posts {
- id String @id @default(auto()) @map("_id") @db.ObjectId
- title String
- content String
- published Boolean
- v Int @map("__v")
-
- - author String @db.ObjectId
- + author users @relation(fields: [authorId], references: [id])
- + authorId String @map("author") @db.ObjectId
-
- categories String[] @db.ObjectId
-}
-
-model users {
- id String @id @default(auto()) @map("_id") @db.ObjectId
- v Int @map("__v")
- email String @unique(map: "email_1")
- name String
- profile UsersProfile?
- + posts posts[]
-}
-```
-
-
-
-
-
-```prisma file=schema.prisma
-type UsersProfile {
- bio String
-}
-
-model categories {
- id String @id @default(auto()) @map("_id") @db.ObjectId
- v Int @map("__v")
- name String
-}
-
-model posts {
- id String @id @default(auto()) @map("_id") @db.ObjectId
- title String
- content String
- published Boolean
- v Int @map("__v")
-
- author users @relation(fields: [authorId], references: [id])
- authorId String @map("author") @db.ObjectId
-
- categories String[] @db.ObjectId
-}
-
-model users {
- id String @id @default(auto()) @map("_id") @db.ObjectId
- v Int @map("__v")
- email String @unique(map: "email_1")
- name String
- profile UsersProfile?
- posts posts[]
-}
-```
-
-
-
-
-
-Update the m-n between `Post` \<-\> `Category` references as follows:
-
-- Rename the `categories` field to `categoryIds` and map it using `@map("categories")` in the `posts` model
-- Add a new `categories` relation field in the `posts` model
-- Add the `postIds` scalar list field in the `categories` model
-- Add the `posts` relation in the `categories` model
-- Add a [relation scalar](/orm/prisma-schema/data-model/relations#annotated-relation-fields) on both models
-- Add the `@relation` attribute specifying the `fields` and `references` arguments on both sides
-
-
-
-
-
-```prisma
-type UsersProfile {
- bio String
-}
-
-model categories {
- id String @id @default(auto()) @map("_id") @db.ObjectId
- v Int @map("__v")
- name String
- + posts posts[] @relation(fields: [postIds], references: [id])
- + postIds String[] @db.ObjectId
-}
-
-model posts {
- id String @id @default(auto()) @map("_id") @db.ObjectId
- title String
- content String
- published Boolean
- v Int @map("__v")
-
- author users @relation(fields: [authorId], references: [id])
- authorId String @map("author") @db.ObjectId
-
- - categories String[] @db.ObjectId
- + categories categories[] @relation(fields: [categoryIds], references: [id])
- + categoryIds String[] @map("categories") @db.ObjectId
-}
-
-model users {
- id String @id @default(auto()) @map("_id") @db.ObjectId
- v Int @map("__v")
- email String @unique(map: "email_1")
- name String
- profile UsersProfile?
- posts posts[]
-}
-```
-
-
-
-
-
-```prisma file=schema.prisma
-type UsersProfile {
- bio String
-}
-
-model categories {
- id String @id @default(auto()) @map("_id") @db.ObjectId
- name String
- v Int @map("__v")
-
- posts posts[] @relation(fields: [postIds], references: [id])
- postIds String[] @db.ObjectId
-}
-
-model posts {
- id String @id @default(auto()) @map("_id") @db.ObjectId
- title String
- content String
- published Boolean
- v Int @map("__v")
-
- author users @relation(fields: [authorId], references: [id])
- authorId String @map("author") @db.ObjectId
-
- categories categories[] @relation(fields: [categoryIds], references: [id])
- categoryIds String[] @db.ObjectId
-}
-
-model users {
- id String @id @default(auto()) @map("_id") @db.ObjectId
- v Int @map("__v")
- email String @unique(map: "email_1")
- name String
- profile UsersProfile?
- posts posts[]
-}
-```
-
-
-
-
-
-### 2.5 Adjust the Prisma schema (optional)
-
-The models that were generated via introspection currently _exactly_ map to your database collections. In this section, you'll learn how you can adjust the naming of the Prisma models to adhere to [Prisma ORM's naming conventions](/orm/reference/prisma-schema-reference#naming-conventions).
-
-Some of these adjustments are entirely optional and you are free to skip to the next step already if you don't want to adjust anything for now. You can go back and make the adjustments at any later point.
-
-As opposed to the current snake_case notation of Prisma models, Prisma ORM's naming conventions are:
-
-- PascalCase for model names
-- camelCase for field names
-
-You can adjust the naming by [_mapping_](/orm/overview/databases/mongodb#using-objectid) the Prisma model and field names to the existing table and column names in the underlying database using `@@map` and `@map`, respectively.
-
-:::tip
-
-You can use the [rename symbol](https://code.visualstudio.com/docs/editor/refactoring#_rename-symbol) operation to refactor model names by highlighting the model name, pressing F2, and finally typing the desired name. This will rename all instances where it is referenced and add the `@@map()` attribute to the existing model with its former name.
-
-:::
-
-If your schema includes a [`versionKey`](https://mongoosejs.com/docs/guide.html#versionKey), update it by adding the `@default(0)` and `@ignore` attributes to the `v` field. This means the field will be excluded from the generated Prisma Client and will have a default value of 0. Prisma ORM does not handle document versioning.
-
-Also note that you can rename [relation fields](/orm/prisma-schema/data-model/relations#relation-fields) to optimize the Prisma Client API that you'll use later to send queries to your database. For example, the `post` field on the `user` model is a _list_, so a better name for this field would be `posts` to indicate that it's plural.
-
-Update the `published` field by including the `@default` attribute to define the default value of the field.
-
-You can also rename the `UserProfile` composite type to `Profile`.
-
-Here's an adjusted version of the Prisma schema that addresses these points:
-
-```prisma file=prisma/schema.prisma highlight=10,14,17,22,25,29,30,38,41,43,46,49;normal showLineNumbers
-generator client {
- provider = "prisma-client-js"
-}
-
-datasource db {
- provider = "mongodb"
- url = env("DATABASE_URL")
-}
-
-//highlight-next-line
-type Profile {
- bio String
-}
-
-//highlight-next-line
-model Category {
- id String @id @default(auto()) @map("_id") @db.ObjectId
- name String
- //highlight-next-line
- v Int @default(0) @map("__v") @ignore
-
- posts Post[] @relation(fields: [post_ids], references: [id])
- post_ids String[] @db.ObjectId
-
- //highlight-next-line
- @@map("categories")
-}
-
-//highlight-next-line
-model Post {
- id String @id @default(auto()) @map("_id") @db.ObjectId
- title String
- content String
- //highlight-start
- published Boolean @default(false)
- v Int @default(0) @map("__v") @ignore
- //highlight-end
-
- author User @relation(fields: [authorId], references: [id])
- authorId String @map("author") @db.ObjectId
-
- categories Category[] @relation(fields: [categoryIds], references: [id])
- categoryIds String[] @db.ObjectId
-
- //highlight-next-line
- @@map("posts")
-}
-
-//highlight-next-line
-model User {
- id String @id @default(auto()) @map("_id") @db.ObjectId
- //highlight-next-line
- v Int @default(0) @map("__v") @ignore
- email String @unique(map: "email_1")
- name String
- //highlight-next-line
- profile Profile?
- posts Post[]
-
- //highlight-next-line
- @@map("users")
-}
-```
-
-## Step 3. Install Prisma Client
-
-As a next step, you can install Prisma Client in your project so that you can start replacing the database queries in your project that are currently made with Mongoose:
-
-```terminal
-npm install @prisma/client
-```
-
-## Step 4. Replace your Mongoose queries with Prisma Client
-
-In this section, we'll show a few sample queries that are being migrated from Mongoose to Prisma Client, based on the example routes from the sample REST API project. For a comprehensive overview of how the Prisma Client API differs from Mongoose, check out the [Mongoose and Prisma API comparison](/orm/more/comparisons/prisma-and-mongoose) page.
-
-First, to set up the `PrismaClient` instance that you'll use to send database queries from the various route handlers, create a new file named `prisma.js` in the `src` directory:
-
-```terminal copy
-touch src/prisma.js
-```
-
-Now, instantiate `PrismaClient` and export it from the file so you can use it in your route handlers later:
-
-```js copy file=src/prisma.js showLineNumbers
-const { PrismaClient } = require('@prisma/client')
-
-const prisma = new PrismaClient()
-
-module.exports = prisma
-```
-
-The imports in our controller files are as follows:
-
-```js file=src/controllers/post.js showLineNumbers
-const Post = require('../models/post')
-const User = require('../models/user')
-const Category = require('../models/category')
-```
-
-```js file=src/controllers/user.js showLineNumbers
-const Post = require('../models/post')
-const User = require('../models/user')
-```
-
-You'll update the controller imports as you migrate from Mongoose to Prisma:
-
-```js file=src/controllers/post.js showLineNumbers
-const prisma = require('../prisma')
-```
-
-```js file=src/controllers/user.js showLineNumbers
-const prisma = require('../prisma')
-```
-
-### 4.1. Replacing queries in `GET` requests
-
-The example REST API used in this guide has four routes that accept `GET` requests:
-
-- `/feed?searchString={searchString}&take={take}&skip={skip}`: Return all published posts
- - Query Parameters (optional):
- - `searchString`: Filter posts by `title` or `content`
- - `take`: Specifies how many objects should be returned in the list
- - `skip`: Specifies how many of the returned objects should be skipped
-- `/post/:id`: Returns a specific post
-- `/authors`: Returns a list of authors
-
-Let's dive into the route handlers that implement these requests.
-
-#### `/feed`
-
-The `/feed` handler is implemented as follows:
-
-```js file=src/controllers/post.js showLineNumbers
-const feed = async (req, res) => {
- try {
- const { searchString, skip, take } = req.query
-
- const or =
- searchString !== undefined
- ? {
- $or: [
- { title: { $regex: searchString, $options: 'i' } },
- { content: { $regex: searchString, $options: 'i' } },
- ],
- }
- : {}
-
- const feed = await Post.find(
- {
- ...or,
- published: true,
- },
- null,
- {
- skip,
- batchSize: take,
- }
- )
- .populate({ path: 'author', model: User })
- .populate('categories')
-
- return res.status(200).json(feed)
- } catch (error) {
- return res.status(500).json(error)
- }
-}
-```
-
-Note that each returned `Post` object includes the relation to the `author` and `category` with which it is associated. With Mongoose, including the relation is not type-safe. For example, if there was a typo in the relation that is retrieved, your database query would fail only at _runtime_ – the JavaScript compiler does not provide any safety here.
-
-Here is how the same route handler is implemented using Prisma Client:
-
-```js file=src/controllers/post.js showLineNumbers
-const feed = async (req, res) => {
- try {
- const { searchString, skip, take } = req.query
-
- const or = searchString
- ? {
- OR: [
- { title: { contains: searchString } },
- { content: { contains: searchString } },
- ],
- }
- : {}
-
- const feed = await prisma.post.findMany({
- where: {
- published: true,
- ...or,
- },
- include: { author: true, categories: true },
- take: Number(take) || undefined,
- skip: Number(skip) || undefined,
- })
-
- return res.status(200).json(feed)
- } catch (error) {
- return res.status(500).json(error)
- }
-}
-```
-
-Note that the way in which Prisma Client includes the `author` relation is absolutely type-safe. The JavaScript compiler would throw an error if you were trying to include a relation that does not exist on the `Post` model.
-
-#### `/post/:id`
-
-The `/post/:id` handler is implemented as follows:
-
-```js file=src/controllers/post.js showLineNumbers
-const getPostById = async (req, res) => {
- const { id } = req.params
-
- try {
- const post = await Post.findById(id)
- .populate({ path: 'author', model: User })
- .populate('categories')
-
- if (!post) return res.status(404).json({ message: 'Post not found' })
-
- return res.status(200).json(post)
- } catch (error) {
- return res.status(500).json(error)
- }
-}
-```
-
-With Prisma ORM, the route handler is implemented as follows:
-
-```js file=src/controllers/post.js showLineNumbers
-const getPostById = async (req, res) => {
- const { id } = req.params
-
- try {
- const post = await prisma.post.findUnique({
- where: { id },
- include: {
- author: true,
- category: true,
- },
- })
-
- if (!post) return res.status(404).json({ message: 'Post not found' })
-
- return res.status(200).json(post)
- } catch (error) {
- return res.status(500).json(error)
- }
-}
-```
-
-### 4.2. Replacing queries in `POST` requests
-
-The REST API has three routes that accept `POST` requests:
-
-- `/user`: Creates a new `User` record
-- `/post`: Creates a new `User` record
-- `/user/:id/profile`: Creates a new `Profile` record for a `User` record with a given ID
-
-#### `/user`
-
-The `/user` handler is implemented as follows:
-
-```js file=src/controllers/user.js showLineNumbers
-const createUser = async (req, res) => {
- const { name, email } = req.body
-
- try {
- const user = await User.create({
- name,
- email,
- })
-
- return res.status(201).json(user)
- } catch (error) {
- return res.status(500).json(error)
- }
-}
-```
-
-With Prisma ORM, the route handler is implemented as follows:
-
-```js file=src/controllers/user.js showLineNumbers
-const createUser = async (req, res) => {
- const { name, email } = req.body
-
- try {
- const user = await prisma.user.create({
- data: {
- name,
- email,
- },
- })
-
- return res.status(201).json(user)
- } catch (error) {
- return res.status(500).json(error)
- }
-}
-```
-
-#### `/post`
-
-The `/post` handler is implemented as follows:
-
-```js file=src/controllers/post.js showLineNumbers
-const createDraft = async (req, res) => {
- const { title, content, authorEmail } = req.body
-
- try {
- const author = await User.findOne({ email: authorEmail })
-
- if (!author) return res.status(404).json({ message: 'Author not found' })
-
- const draft = await Post.create({
- title,
- content,
- author: author._id,
- })
-
- res.status(201).json(draft)
- } catch (error) {
- return res.status(500).json(error)
- }
-}
-```
-
-With Prisma ORM, the route handler is implemented as follows:
-
-```js file=src/controllers/post.js showLineNumbers
-const createDraft = async (req, res) => {
- const { title, content, authorEmail } = req.body
-
- try {
- const draft = await prisma.post.create({
- data: {
- title,
- content,
- author: {
- connect: {
- email: authorEmail,
- },
- },
- },
- })
-
- res.status(201).json(draft)
- } catch (error) {
- return res.status(500).json(error)
- }
-}
-```
-
-Note that Prisma Client's nested write here saves the initial query where the `User` record is first retrieved by its `email`. That's because, with Prisma Client you can connect records in relations using any unique property.
-
-#### `/user/:id/profile`
-
-The `/user/:id/profile` handler is implemented as follows:
-
-```js file=src/controllers/user.js showLineNumbers
-const setUserBio = async (req, res) => {
- const { id } = req.params
- const { bio } = req.body
-
- try {
- const user = await User.findByIdAndUpdate(
- id,
- {
- profile: {
- bio,
- },
- },
- { new: true }
- )
-
- if (!user) return res.status(404).json({ message: 'Author not found' })
-
- return res.status(200).json(user)
- } catch (error) {
- return res.status(500).json(error)
- }
-}
-```
-
-With Prisma ORM, the route handler is implemented as follows:
-
-```js file=src/controllers/user.js showLineNumbers
-const setUserBio = async (req, res) => {
- const { id } = req.params
- const { bio } = req.body
-
- try {
- const user = await prisma.user.update({
- where: { id },
- data: {
- profile: {
- bio,
- },
- },
- })
-
- if (!user) return res.status(404).json({ message: 'Author not found' })
-
- return res.status(200).json(user)
- } catch (error) {
- console.log(error)
- return res.status(500).json(error)
- }
-}
-```
-
-Alternatively, you can use the `set` property to update the value of an embedded document as follows:
-
-```js file=src/controllers/user.js showLineNumbers
-const setUserBio = async (req, res) => {
- const { id } = req.params
- const { bio } = req.body
-
- try {
- const user = await prisma.user.update({
- where: {
- id,
- },
- data: {
- profile: {
- set: { bio },
- },
- },
- })
-
- return res.status(200).json(user)
- } catch (error) {
- console.log(error)
- return res.status(500).json(error)
- }
-}
-```
-
-### 4.3. Replacing queries in `PUT` requests
-
-The REST API has two routes that accept a `PUT` request:
-
-- `/post/:id/:categoryId`: Adds the post with `:id` to the category with `:categoryId`
-- `/post/:id`: Updates the `published` status of a post to true.
-
-Let's dive into the route handlers that implement these requests.
-
-#### `/post/:id/:categoryId`
-
-The `/post/:id/:categoryId` handler is implemented as follows:
-
-```js file=src/controllers/post.js showLineNumbers
-const addPostToCategory = async (req, res) => {
- const { id, categoryId } = req.params
-
- try {
- const category = await Category.findById(categoryId)
-
- if (!category)
- return res.status(404).json({ message: 'Category not found' })
-
- const post = await Post.findByIdAndUpdate(
- { _id: id },
- {
- categories: [{ _id: categoryId }],
- },
- { new: true }
- )
-
- if (!post) return res.status(404).json({ message: 'Post not found' })
- return res.status(200).json(post)
- } catch (error) {
- return res.status(500).json(error)
- }
-}
-```
-
-With Prisma ORM, the handler is implemented as follows:
-
-```js file=src/controllers/post.js showLineNumbers
-const addPostToCategory = async (req, res) => {
- const { id, categoryId } = req.query
-
- try {
- const post = await prisma.post.update({
- where: {
- id,
- },
- data: {
- categories: {
- connect: {
- id: categoryId,
- },
- },
- },
- })
-
- if (!post) return res.status(404).json({ message: 'Post not found' })
-
- return res.status(200).json(post)
- } catch (error) {
- console.log({ error })
- return res.status(500).json(error)
- }
-}
-```
-
-#### `/post/:id`
-
-The `/post/:id` handler is implemented as follows:
-
-```js file=src/controllers/post.js showLineNumbers
-const publishDraft = async (req, res) => {
- const { id } = req.params
-
- try {
- const post = await Post.findByIdAndUpdate(
- { id },
- { published: true },
- { new: true }
- )
- return res.status(200).json(post)
- } catch (error) {
- return res.status(500).json(error)
- }
-}
-```
-
-With Prisma ORM, the handler is implemented as follows:
-
-```js file=src/controllers/post.js showLineNumbers
-const publishDraft = async (req, res) => {
- const { id } = req.params
-
- try {
- const post = await prisma.post.update({
- where: { id },
- data: { published: true },
- })
- return res.status(200).json(post)
- } catch (error) {
- return res.status(500).json(error)
- }
-}
-```
-
-## More
-
-### Embedded documents `_id` field
-
-By default, Mongoose assigns each document and embedded document an `_id` field. If you wish to disable this option for embedded documents, you can set the `_id` option to false.
-
-```js
-const ProfileSchema = new Schema(
- {
- bio: String,
- },
- {
- _id: false,
- }
-)
-```
-
-### Document version key
-
-Mongoose assigns each document a version when created. You can disable Mongoose from versioning your documents by setting the `versionKey` option of a model to false. It is [not recommended](http://aaronheckmann.blogspot.com/2012/06/mongoose-v3-part-1-versioning.html) to disable this unless you are an advanced user.
-
-```js
-const ProfileSchema = new Schema(
- {
- bio: String,
- },
- {
- versionKey: false,
- }
-)
-```
-
-When migrating to Prisma ORM, mark the `versionKey` field as optional ( **?** ) in your Prisma schema and add the `@ignore` attribute to exclude it from Prisma Client.
-
-### Collection name inference
-
-Mongoose infers the collection names by automatically converting the model names to lowercase and plural form.
-
-On the other hand, Prisma ORM maps the model name to the table name in your database [modeling your data](/orm/prisma-schema/data-model/models).
-
-You can enforce the collection name in Mongoose to have the same name as the model by setting the [](https://mongoosejs.com/docs/guide.html#collection) option while creating your schema
-
-```js
-const PostSchema = new Schema(
- {
- title: String,
- content: String,
- // more fields here
- },
- {
- collection: 'Post',
- }
-)
-```
-
-### Modeling relations
-
-You can model relations in Mongoose between documents by either using [sub-documents](https://mongoosejs.com/docs/subdocs.html) or storing [a reference to other documents](https://mongoosejs.com/docs/queries.html#refs).
-
-Prisma ORM allows you to model different types of relations between documents when working with MongoDB:
-
-- [One-to-one relations](/orm/prisma-schema/data-model/relations/one-to-one-relations#mongodb)
-- [One-to-many relations](/orm/prisma-schema/data-model/relations/one-to-many-relations#mongodb)
-- [Many-to-many relations](/orm/prisma-schema/data-model/relations/many-to-many-relations#mongodb)
-- [Self-relations](/orm/prisma-schema/data-model/relations/self-relations#mongodb)
-- [Embedded documents](/orm/prisma-schema/data-model/models#defining-composite-types)
diff --git a/content/200-orm/800-more/450-migrating-to-prisma/index.mdx b/content/200-orm/800-more/450-migrating-to-prisma/index.mdx
deleted file mode 100644
index f77eeb6144..0000000000
--- a/content/200-orm/800-more/450-migrating-to-prisma/index.mdx
+++ /dev/null
@@ -1,10 +0,0 @@
----
-title: 'Migrate to Prisma ORM'
-metaTitle: 'Migrate to Prisma ORM from other ORMs'
-metaDescription: 'How to migrate to Prisma ORM from other ORMs and query builders.'
-hide_table_of_contents: true
----
-
-## In this section
-
-
diff --git a/content/800-guides/1000-using-prisma-orm-with-turborepo.mdx b/content/800-guides/1000-using-prisma-orm-with-turborepo.mdx
new file mode 100644
index 0000000000..d5398d1daf
--- /dev/null
+++ b/content/800-guides/1000-using-prisma-orm-with-turborepo.mdx
@@ -0,0 +1,537 @@
+---
+title: 'Using Prisma with Turborepo'
+metaTitle: 'Using Prisma with Turborepo'
+metaDescription: 'Learn step-by-step how to integrate Prisma ORM with Turborepo to build modular, scalable monorepo architectures efficiently.'
+sidebar_label: 'Prisma with Turborepo'
+image: '/img/guides/prisma-turborepo-setup.png'
+tags:
+ - Turborepo
+ - Monorepo
+---
+
+Prisma is a powerful ORM for managing databases, and [Turborepo](https://turbo.build/) simplifies monorepo workflows. By combining these tools, you can create a scalable, modular architecture for your projects.
+
+This guide will show you how to set up Prisma as a standalone package in a Turborepo monorepo, enabling efficient configuration, type sharing, and database management across multiple apps.
+
+### What you'll learn:
+
+- How to set up Prisma in a Turborepo monorepo.
+- Steps to generate and reuse PrismaClient across packages.
+- Integrating the Prisma package into other applications in the monorepo.
+
+:::note
+
+This guide was tested using Turborepo version `2.3.3` and Prisma ORM version `6.1.0`.
+
+:::
+
+## 1. Create your monorepo using turborepo
+
+To set up a Turborepo monorepo named `hello-world`, run the following command:
+
+```terminal
+npx create-turbo@latest hello-world
+```
+
+After the setup, choose a package manager for the project. Navigate to the project root directory and install Turborepo as a development dependency:
+
+
+
+
+
+```terminal
+cd ./hello-world
+npm install turbo --save-dev
+```
+
+
+
+
+
+```terminal
+cd ./hello-world
+yarn add turbo --dev --ignore-workspace-root-check
+```
+
+
+
+
+
+```terminal
+cd ./hello-world
+pnpm add turbo --save-dev --ignore-workspace-root-check
+```
+
+
+
+
+
+For more information about installing Turborepo, refer to the [official Turborepo guide](https://turbo.build/repo/docs/getting-started/installation).
+
+## 2. Add a new `database` package to the `hello-world` monorepo
+
+Create a `database` package within the `packages` directory. Then, create a `package.json` file for the package by running:
+
+```terminal
+cd packages/
+mkdir database
+cd database
+touch package.json
+```
+
+Define the `package.json` file as follows:
+
+```json
+{
+ "name": "@repo/db",
+ "version": "0.0.0"
+}
+```
+
+Next, install the required dependencies to use Prisma ORM. Use your preferred package manager:
+
+
+
+
+
+```terminal
+npm install prisma --save-dev
+npm install @prisma/client
+```
+
+
+
+
+
+```terminal
+yarn add prisma --dev
+yarn add @prisma/client
+```
+
+
+
+
+
+```terminal
+pnpm add prisma --save-dev
+pnpm add @prisma/client
+```
+
+
+
+
+
+## 3. Initialize prisma by running `prisma init`
+
+Inside the `database` directory, initialize prisma by running:
+
+
+
+
+
+ ```terminal
+ npx prisma init
+ ```
+
+
+
+
+
+ ```terminal
+ yarn prisma init
+ ```
+
+
+
+
+
+ ```terminal
+ pnpm prisma init
+ ```
+
+
+
+
+
+This should create several files inside `packages/database`:
+
+- `schema.prisma` is where your [Prisma schema](/orm/prisma-schema/overview) lives. Here, you'll be able to modify the shape of your database. The `prisma init` command by default will create a configuration for `PostgreSQL` to be used. You can modify the schema to use any other [supported database](/orm/reference/supported-databases) by Prisma ORM.
+- `.gitignore` adds some ignored files to git
+- `.env` lets you manually specify your `DATABASE_URL` for prisma.
+
+:::warning
+
+Make sure to replace the `DATABASE_URL` inside `packages/database/.env` with a valid database url.
+
+:::
+
+Add a model to your Prisma schema in `database/prisma/schema.prisma`:
+
+```prisma
+datasource db {
+ provider = "postgresql"
+ url = env("DATABASE_URL")
+}
+
+generator client {
+ provider = "prisma-client-js"
+ output = "../generated/client"
+}
+
+model User {
+ id Int @id @default(autoincrement())
+ createdAt DateTime @default(now())
+ email String @unique
+ name String?
+}
+```
+
+### The importance of generating Prisma types in a [custom directory](/orm/prisma-client/setup-and-configuration/generating-prisma-client#using-a-custom-output-path)
+
+In the `schema.prisma` file, we specify a custom `output` path where Prisma will generate its types. This ensures Prisma's types are resolved correctly across different package managers.
+
+> In this guide, the types will be generated in the `database/generated/client` directory.
+
+## 4. Create scripts to execute Prisma CLI commands
+
+Let's add some scripts to the `package.json` inside `packages/database`:
+
+```json
+{
+ "scripts": {
+ "db:generate": "prisma generate",
+ "db:migrate": "prisma migrate dev --skip-generate",
+ "db:deploy": "prisma migrate deploy"
+ }
+}
+```
+
+Let's also add these scripts to `turbo.json` in the root:
+
+```json
+{
+ "tasks": {
+ "db:generate": {
+ "cache": false
+ },
+ "db:migrate": {
+ "cache": false,
+ "persistent": true // This is necessary to interact with the CLI and assign names to your database migrations.
+ },
+ "db:deploy": {
+ "cache": false
+ }
+ }
+}
+```
+
+#### 1. Migrate your `prisma.schema` and generate types
+
+Navigate to the project root and run the following command to automatically migrate our database:
+
+
+
+
+
+ ```terminal
+ npx turbo db:migrate
+ ```
+
+
+
+
+
+ ```terminal
+ yarn turbo db:migrate
+ ```
+
+
+
+
+
+ ```terminal
+ pnpm turbo db:migrate
+ ```
+
+
+
+
+
+
+#### 2. Generate your `prisma.schema`
+
+To generate the types from Prisma schema, from the project root run:
+
+
+
+
+
+ ```terminal
+ npx turbo db:generate
+ ```
+
+
+
+
+
+ ```terminal
+ yarn turbo db:generate
+ ```
+
+
+
+
+
+ ```terminal
+ pnpm turbo db:generate
+ ```
+
+
+
+
+
+## 5. Export prisma types and an instance of `PrismaClient` to be used across the monorepo
+
+Next, export the generated types and an instance of `PrismaClient` so it can used in your applications.
+
+In the `packages/database` directory, create a `src` folder and add a `client.ts` file. This file will define an instance of `PrismaClient`:
+
+```ts file=packages/database/src/client.ts
+import { PrismaClient } from "../generated/client";
+
+const globalForPrisma = global as unknown as { prisma: PrismaClient };
+
+export const prisma =
+ globalForPrisma.prisma || new PrismaClient();
+
+if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;
+```
+
+Then create an `index.ts` file in the `src` folder to re-export the generated prisma types and the `PrismaClient` instance:
+
+```ts file=packages/database/src/index.ts
+export { prisma } from './client' // exports instance of prisma
+export * from "../generated/client" // exports generated types from prisma
+```
+
+Follow the [Just-in-Time packaging pattern](https://turbo.build/repo/docs/core-concepts/internal-packages#just-in-time-packages) and create an entrypoint to the package inside `packages/database/package.json`:
+
+```json
+{
+ "exports": {
+ ".": "./src/index.ts"
+ }
+}
+```
+
+By completing these steps, you'll make the Prisma types and `PrismaClient` instance accessible throughout the monorepo.
+
+## 6. Importing the `database` package into the `web` app in the monorepo
+
+The `hello-world` project should have an app called `web` at `apps/web`. Add the `database` dependency to `apps/web/package.json`:
+
+
+
+
+
+ ```json
+ {
+ "dependencies": {
+ "@repo/db": "*"
+ }
+ }
+ ```
+
+
+
+
+
+ ```json
+ {
+ "dependencies": {
+ "@repo/db": "*"
+ }
+ }
+ ```
+
+
+
+
+
+ ```json
+ {
+ "dependencies": {
+ "@repo/db": "workspace:*"
+ }
+ }
+ ```
+
+
+
+
+
+Run your package manager's install command inside the `apps/web` directory:
+
+
+
+
+
+ ```terminal
+ cd apps/web
+ npm install
+ ```
+
+
+
+
+
+ ```terminal
+ cd apps/web
+ yarn install
+ ```
+
+
+
+
+
+ ```terminal
+ cd apps/web
+ pnpm install
+ ```
+
+
+
+
+Let's import the intantiated `prisma` client from the `database` package in the `web` app in the `page.tsx` file:
+
+```tsx
+import styles from "./page.module.css";
+import { prisma } from "@repo/db";
+
+export default async function Home() {
+ const user = await prisma.user.findFirst()
+ return (
+
+ {user?.name ?? "No user added yet"}
+
+ );
+}
+```
+
+Then create a `.env` file in the `web` directory and copy of the contents of the `.env` file in the `database` directory containing the `DATABASE_URL`.:
+
+```env
+DATABASE_URL="Same database url as used in the database directory"
+```
+
+:::note
+
+If you want to use a single `.env` file in the root directory across your apps and packages in a Turborepo setup, consider using a package like [`dotenvx`](https://dotenvx.com/docs/monorepos/turborepo).
+
+To implement this, update the `package.json` files for each package or app to ensure they load the required environment variables from the shared `.env` file. For detailed instructions, refer to the [`dotenvx` guide for Turborepo](https://dotenvx.com/docs/monorepos/turborepo).
+
+Keep in mind that Turborepo [recommends using separate `.env` files for each package](https://turbo.build/repo/docs/crafting-your-repository/using-environment-variables#use-env-files-in-packages) to promote modularity and avoid potential conflicts.
+
+
+:::
+
+## 7. Setup dependent tasks
+
+The `db:generate` and `db:deploy` scripts are not yet optimized for the monorepo setup but are essential for the `dev` and `build` tasks.
+
+If a new developer runs `turbo dev` on an application without first running `db:generate`, they will encounter errors.
+
+To prevent this, ensure that `db:generate` is always executed before running `dev` or `build`. Additionally, make sure both `db:deploy` and `db:generate` are executed before `db:build`. Here's how to configure this in your `turbo.json` file:
+
+```json
+{
+ "tasks": {
+ "dev": {
+ "dependsOn": ["^db:generate"],
+ "cache": false
+ // Additional configuration for dev tasks
+ },
+ "build": {
+ "dependsOn": ["^db:generate"],
+ // Additional configuration for build tasks
+ }
+ }
+}
+```
+
+## 8. Run the project in development
+
+Then from the project root run the project:
+
+
+
+
+
+ ```terminal
+ npx turbo run dev --filter=web
+ ```
+
+
+
+
+
+ ```terminal
+ yarn turbo run dev --filter=web
+ ```
+
+
+
+
+
+ ```terminal
+ pnpm turbo run dev --filter=web
+ ```
+
+
+
+
+
+Navigate to the `http://localhost:3000` and you should see the message:
+
+```
+No user added yet
+```
+
+:::note
+
+You can add users to your database by creating a seed script or manually by using [Prisma Studio](/orm/tools/prisma-studio).
+
+To use Prisma Studio to add manually data via a GUI, navigate inside the `packages/database` directory and run `prisma studio` using your package manager:
+
+
+
+
+
+ ```terminal
+ npx prisma studio
+ ```
+
+
+
+
+
+ ```terminal
+ yarn prisma studio
+ ```
+
+
+
+
+
+ ```terminal
+ pnpm prisma studio
+ ```
+
+
+
+
+This command starts a server with a GUI at http://localhost:5555, allowing you to view and modify your data.
+
+:::
+
+Congratulations, you're done setting up Prisma for Turborepo!
diff --git a/content/800-guides/300-data-migration-with-expand-and-contract.mdx b/content/800-guides/300-data-migration-with-expand-and-contract.mdx
new file mode 100644
index 0000000000..119dfe10a1
--- /dev/null
+++ b/content/800-guides/300-data-migration-with-expand-and-contract.mdx
@@ -0,0 +1,235 @@
+---
+title: 'How to migrate data using the expand and contract pattern'
+metaTitle: 'How to migrate data using the expand and contract pattern'
+metaDescription: 'Learn how to perform data migrations using the expand and contract pattern with Prisma ORM'
+sidebar_label: 'Data migration with expand and contract'
+image: '/img/guides/data-migration-cover.png'
+tags:
+ - migration
+ - data-migration
+ - schema
+ - database
+ - prisma-migrate
+ - production
+ - postgresql
+ - expand-and-contract
+ - schema-evolution
+ - best-practices
+ - git
+ - deployment
+ - ci-cd
+---
+
+## Introduction
+
+When making changes to your database schema in production, it's crucial to ensure data consistency and avoid downtime. This guide shows you how to use the expand and contract pattern to safely migrate data between columns. We'll walk through a practical example of replacing a boolean field with an enum field while preserving existing data.
+
+## Prerequisites
+
+Before starting this guide, make sure you have:
+
+- Node.js installed (version 18 or higher)
+- A Prisma ORM project with an existing schema
+- A supported database (PostgreSQL, MySQL, SQLite, SQL Server, etc.)
+- Access to both development and production databases
+- Basic understanding of Git branching
+- Basic familiarity with TypeScript
+
+## 1. Set up your environment
+
+### 1.1. Review initial schema
+
+Start with a basic schema containing a Post model:
+
+```prisma
+generator client {
+ provider = "prisma-client-js"
+}
+
+datasource db {
+ provider = "postgresql"
+ url = env("DATABASE_URL")
+}
+
+model Post {
+ id Int @id @default(autoincrement())
+ title String
+ content String?
+ published Boolean @default(false)
+}
+```
+
+### 1.2. Create a development branch
+
+Create a new branch for your changes:
+
+```bash
+git checkout -b create-status-field
+```
+
+## 2. Expand the schema
+
+### 2.1. Add new column
+
+Update your schema to add the new Status enum and field:
+
+```prisma
+model Post {
+ id Int @id @default(autoincrement())
+ title String
+ content String?
+ published Boolean? @default(false)
+ status Status @default(Unknown)
+}
+
+enum Status {
+ Unknown
+ Draft
+ InProgress
+ InReview
+ Published
+}
+```
+
+### 2.2. Create migration
+
+Generate the migration:
+
+```bash
+npx prisma migrate dev --name add-status-column
+```
+
+## 3. Migrate the data
+
+### 3.1. Create migration script
+
+Create a new TypeScript file for the data migration:
+
+```typescript
+import { PrismaClient } from '@prisma/client'
+
+const prisma = new PrismaClient()
+
+async function main() {
+ await prisma.$transaction(async (tx) => {
+ const posts = await tx.post.findMany()
+ for (const post of posts) {
+ await tx.post.update({
+ where: { id: post.id },
+ data: {
+ status: post.published ? 'Published' : 'Unknown',
+ },
+ })
+ }
+ })
+}
+
+main()
+ .catch(async (e) => {
+ console.error(e)
+ process.exit(1)
+ })
+ .finally(async () => await prisma.$disconnect())
+```
+
+### 3.2. Set up migration script
+
+Add the migration script to your package.json:
+
+```json
+{
+ "scripts": {
+ "data-migration:add-status-column": "tsx ./prisma/migrations//data-migration.ts"
+ }
+}
+```
+
+### 3.3. Execute migration
+
+1. Update your DATABASE_URL to point to the production database
+2. Run the migration script:
+
+```bash
+npm run data-migration:add-status-column
+```
+
+## 4. Contract the schema
+
+### 4.1. Create cleanup branch
+
+Create a new branch for removing the old column:
+
+```bash
+git checkout -b drop-published-column
+```
+
+### 4.2. Remove old column
+
+Update your schema to remove the published field:
+
+```prisma
+model Post {
+ id Int @id @default(autoincrement())
+ title String
+ content String?
+ status Status @default(Unknown)
+}
+
+enum Status {
+ Draft
+ InProgress
+ InReview
+ Published
+}
+```
+
+### 4.3. Generate cleanup migration
+
+Create and run the final migration:
+
+```bash
+npx prisma migrate dev --name drop-published-column
+```
+
+## 5. Deploy to production
+
+### 5.1. Set up deployment
+
+Add the following command to your CI/CD pipeline:
+
+```bash
+npx prisma migrate deploy
+```
+
+### 5.2. Monitor deployment
+
+Watch for any errors in your logs and monitor your application's behavior after deployment.
+
+## Troubleshooting
+
+### Common issues and solutions
+
+1. **Migration fails due to missing default**
+ - Ensure you've added a proper default value
+ - Check that all existing records can be migrated
+
+2. **Data loss prevention**
+ - Always backup your database before running migrations
+ - Test migrations on a copy of production data first
+
+3. **Transaction rollback**
+ - If the data migration fails, the transaction will automatically rollback
+ - Fix any errors and retry the migration
+
+## Next steps
+
+Now that you've completed your first expand and contract migration, you can:
+
+- Learn more about [Prisma Migrate](/orm/prisma-migrate)
+- Explore [schema prototyping](/orm/prisma-migrate/workflows/prototyping-your-schema)
+- Understand [customizing migrations](/orm/prisma-migrate/workflows/customizing-migrations)
+
+For more information and updates:
+- [Expand and Contract Pattern Documentation](https://www.prisma.io/dataguide/types/relational/expand-and-contract-pattern)
+- [Prisma Migrate Workflows](/orm/prisma-migrate/workflows)
+- Join our [Discord community](https://discord.com/invite/prisma)
diff --git a/content/800-guides/400-implementing-schema-changes.mdx b/content/800-guides/400-implementing-schema-changes.mdx
new file mode 100644
index 0000000000..f7c2e5368d
--- /dev/null
+++ b/content/800-guides/400-implementing-schema-changes.mdx
@@ -0,0 +1,219 @@
+---
+title: 'How to manage schema changes in a team'
+metaTitle: 'How to manage schema changes in a team with Prisma Migrate'
+metaDescription: 'Learn how to use Prisma Migrate effectively when collaborating on a project as a team'
+sidebar_label: 'Team schema changes'
+image: '/img/guides/schema-migration-cover.png'
+---
+
+## Introduction
+
+When working in a team, managing database schema changes can be challenging. This guide shows you how to effectively collaborate on schema changes using Prisma Migrate, ensuring that all team members can safely contribute to and incorporate schema changes.
+
+## Prerequisites
+
+Before starting this guide, make sure you have:
+
+- Node.js installed (version 18 or higher)
+- A Prisma project set up with migrations
+- A relational database (PostgreSQL, MySQL, SQLite, SQL Server, etc.)
+- Basic understanding of Git
+- Basic familiarity with Prisma Migrate
+
+:::warning
+
+This guide **does not apply for MongoDB**.
+Instead of `migrate dev`, [`db push`](/orm/prisma-migrate/workflows/prototyping-your-schema) is used for [MongoDB](/orm/overview/databases/mongodb).
+
+:::
+
+## 1. Understand migration basics
+
+### 1.1. Migration order
+
+Migrations are **applied in the same order as they were created**. The creation date is part of the migration subfolder name - for example, `20210316081837-updated-fields` was created on `2021-03-16-08:18:37`.
+
+### 1.2. Source control requirements
+
+You should commit the following files to source control:
+
+- The contents of the `.prisma/migrations` folder, including the `migration_lock.toml` file
+- The Prisma Schema (`schema.prisma`)
+
+Source-controlling the `schema.prisma` file is not enough - you must include your migration history because:
+
+- Customized migrations contain information that cannot be represented in the Prisma schema
+- The `prisma migrate deploy` command only runs migration files
+
+## 2. Incorporate team changes
+
+### 2.1. Pull latest changes
+
+To incorporate changes from collaborators:
+
+1. Pull the changed Prisma schema and `./prisma/migrations` folder
+2. Run the migrate command:
+
+```terminal
+npx prisma migrate dev
+```
+
+### 2.2. Example scenario
+
+Let's walk through a sample scenario with three developers sharing schema changes:
+
+
+
+
+
+```prisma file=schema.prisma
+model Post {
+ id Int @id @default(autoincrement())
+ title String
+ content String?
+ published Boolean @default(false)
+ author User? @relation(fields: [authorId], references: [id])
+ authorId Int?
+}
+
+model User {
+ id Int @id @default(autoincrement())
+ email String @unique
+ name String?
+ posts Post[]
+}
+```
+
+
+
+
+
+```prisma file=schema.prisma
+model Post {
+ id Int @id @default(autoincrement())
+ title String
+ content String?
+ published Boolean @default(false)
+ author User? @relation(fields: [authorId], references: [id])
+ authorId Int?
+}
+
+model User {
+ id Int @id @default(autoincrement())
+ email String @unique
+ name String?
+ //add-start
+ favoriteColor String? // Added by Ania
+ bestPacmanScore Int? // Added by you
+ //add-end
+ posts Post[]
+}
+
+//add-start
+// Added by Javier
+model Tag {
+ tagName String @id
+ tagCategory Category
+}
+//add-end
+```
+
+
+
+
+## 3. Handle concurrent changes
+
+### 3.1. Developer A's changes
+
+Ania adds a new field:
+
+```prisma
+model User {
+ /* ... */
+ favoriteColor String?
+}
+```
+
+And generates a migration:
+
+```terminal
+npx prisma migrate dev --name new-field
+```
+
+### 3.2. Developer B's changes
+
+Javier adds a new model:
+
+```prisma
+model Tag {
+ tagName String @id
+ tagCategory Category
+}
+```
+
+And generates a migration:
+
+```terminal
+npx prisma migrate dev --name new-model
+```
+
+### 3.3. Merge changes
+
+The migration history now has two new migrations:
+
+
+
+## 4. Integrate your changes
+
+### 4.1. Pull team changes
+
+1. Pull the most recent changes:
+ - Two new migrations
+ - Updated schema file
+
+2. Review the merged schema:
+
+```prisma
+model User {
+ /* ... */
+ favoriteColor String?
+ bestPacmanScore Int?
+}
+
+model Tag {
+ tagName String @id
+ tagCategory Category
+ posts Post[]
+}
+```
+
+### 4.2. Generate your migration
+
+Run the migrate command:
+
+```terminal
+npx prisma migrate dev
+```
+
+This will:
+1. Apply your team's migrations
+2. Create a new migration for your changes
+3. Apply your new migration
+
+### 4.3. Commit changes
+
+Commit:
+- The merged `schema.prisma`
+- Your new migration file
+
+## Next steps
+
+Now that you understand team schema management, you can:
+
+- Learn about [customizing migrations](/orm/prisma-migrate/workflows/customizing-migrations)
+- Explore [deployment workflows](/orm/prisma-migrate/workflows/development-and-production)
+
+For more information and updates:
+- [Prisma Migrate documentation](/orm/prisma-migrate)
+- [Team development workflows](/orm/prisma-migrate/workflows/team-development)
+- Join our [Discord community](https://discord.com/invite/prisma)
diff --git a/content/800-guides/500-migrate-from-typeorm.mdx b/content/800-guides/500-migrate-from-typeorm.mdx
new file mode 100644
index 0000000000..8735a9e1a9
--- /dev/null
+++ b/content/800-guides/500-migrate-from-typeorm.mdx
@@ -0,0 +1,208 @@
+---
+title: 'How to migrate from TypeORM to Prisma ORM'
+metaTitle: 'How to migrate from TypeORM to Prisma ORM'
+metaDescription: 'Learn how to migrate from TypeORM to Prisma ORM'
+sidebar_label: 'Migrate from TypeORM'
+image: '/img/guides/migrate-from-typeorm-cover.png'
+---
+
+# How to migrate from TypeORM to Prisma ORM
+
+## Introduction
+
+This guide shows you how to migrate your application from TypeORM to Prisma ORM. We'll use an extended version of the [TypeORM Express example](https://github.com/typeorm/typescript-express-example/) as a [sample project](https://github.com/prisma/migrate-from-typeorm-to-prisma) to demonstrate the migration steps.
+
+This migration guide uses PostgreSQL as the example database, but it equally applies to any other relational database that's [supported by Prisma ORM](/orm/reference/supported-databases). You can learn how Prisma ORM compares to TypeORM on the [Prisma ORM vs TypeORM](/orm/more/comparisons/prisma-and-typeorm) page.
+
+## Prerequisites
+
+Before starting this guide, make sure you have:
+
+- A TypeORM project you want to migrate
+- Node.js installed (version 16 or higher)
+- PostgreSQL or another supported database
+- Basic familiarity with TypeORM and Express.js
+
+## 2. Prepare for migration
+
+### 2.1. Understand the migration process
+
+The steps for migrating from TypeORM to Prisma ORM are always the same, no matter what kind of application or API layer you're building:
+
+1. Install the Prisma CLI
+2. Introspect your database
+3. Create a baseline migration
+4. Install Prisma Client
+5. Gradually replace your TypeORM queries with Prisma Client
+
+These steps apply whether you're building a REST API (e.g., with Express, Koa, or NestJS), a GraphQL API (e.g., with Apollo Server, TypeGraphQL, or Nexus), or any other kind of application that uses TypeORM for database access.
+
+### 2.2. Set up Prisma configuration
+
+Create a new Prisma schema file:
+
+```terminal
+npx prisma init
+```
+
+Update the `DATABASE_URL` in the `.env` file with your database connection string:
+
+```env
+DATABASE_URL="postgresql://USER:PASSWORD@HOST:PORT/DATABASE"
+```
+
+## 3. Migrate the database schema
+
+### 3.1. Introspect your database
+
+Run Prisma's introspection to create the Prisma schema from your existing database:
+
+```terminal
+npx prisma db pull
+```
+
+This will create a `schema.prisma` file with your database schema.
+
+### 3.2. Create a baseline migration
+
+Create and apply a baseline migration to mark the current state of your database:
+
+```terminal
+npx prisma migrate diff --from-empty --to-schema-datamodel prisma/schema.prisma --script > baseline.sql
+npx prisma migrate resolve --applied "baseline"
+```
+
+## 4. Update your application code
+
+### 4.1. Install Prisma Client
+
+Install the Prisma Client package:
+
+```terminal
+npm install @prisma/client
+```
+
+Generate Prisma Client:
+
+```terminal
+npx prisma generate
+```
+
+### 4.2. Replace TypeORM queries
+
+Start replacing your TypeORM queries with Prisma Client. Here's an example of how to convert some common queries:
+
+
+
+
+
+```typescript
+// Find one
+const user = await userRepository.findOne({
+ where: { id: 1 }
+});
+
+// Create
+const user = await userRepository.save({
+ email: 'alice@prisma.io',
+ name: 'Alice'
+});
+
+// Update
+await userRepository.update(1, {
+ name: 'New name'
+});
+
+// Delete
+await userRepository.delete(1);
+```
+
+
+
+
+
+```typescript
+// Find one
+const user = await prisma.user.findUnique({
+ where: { id: 1 }
+});
+
+// Create
+const user = await prisma.user.create({
+ data: {
+ email: 'alice@prisma.io',
+ name: 'Alice'
+ }
+});
+
+// Update
+await prisma.user.update({
+ where: { id: 1 },
+ data: { name: 'New name' }
+});
+
+// Delete
+await prisma.user.delete({
+ where: { id: 1 }
+});
+```
+
+
+
+
+
+### 4.3. Update your controllers
+
+Update your Express controllers to use Prisma Client. For example, here's how to update the `CreateUserAction`:
+
+```typescript
+import { prisma } from '../client'
+
+export class CreateUserAction {
+ async run(req: Request, res: Response) {
+ const { email, name } = req.body
+
+ const result = await prisma.user.create({
+ data: {
+ email,
+ name,
+ },
+ })
+
+ return res.json(result)
+ }
+}
+```
+
+## 5. Test and deploy
+
+### 5.1. Test your changes
+
+Test all migrated endpoints to ensure they work as expected:
+
+```bash
+npm test
+```
+
+### 5.2. Deploy your changes
+
+1. Deploy your schema changes:
+```bash
+npx prisma migrate deploy
+```
+
+2. Deploy your application code with the updated dependencies.
+
+## Next steps
+
+Now that you've migrated to Prisma ORM, you can:
+
+- Add more complex queries using Prisma's powerful query API
+- Set up Prisma Studio for database management
+- Implement database monitoring
+- Add automated tests using Prisma's testing utilities
+
+For more information and updates:
+- [Prisma ORM documentation](/orm)
+- [Prisma Client API reference](/orm/prisma-client)
+- Join our [Discord community](https://discord.com/invite/prisma)
diff --git a/content/800-guides/5000-guide-on-making-guides.mdx b/content/800-guides/5000-guide-on-making-guides.mdx
new file mode 100644
index 0000000000..1a9ea8dd39
--- /dev/null
+++ b/content/800-guides/5000-guide-on-making-guides.mdx
@@ -0,0 +1,177 @@
+---
+title: 'How to write guides for Prisma ORM'
+metaTitle: 'How to write guides for Prisma ORM'
+metaDescription: 'Learn how to write clear, consistent, and helpful guides for Prisma ORM documentation'
+sidebar_label: 'Guide writing guide'
+image: '/img/guides/guide-writing-guide-cover.png'
+---
+
+## Introduction
+
+This guide shows you how to write guides for Prisma ORM documentation. It covers the required structure, formatting, and style conventions to ensure consistency across all guides. You'll learn about frontmatter requirements, section organization, and writing style.
+
+## Prerequisites
+
+Before writing a guide, make sure you have:
+
+- A clear understanding of the topic you're writing about
+- Access to the Prisma documentation repository
+- Familiarity with Markdown and MDX
+- Knowledge of the target audience for your guide
+
+## Guide structure
+
+### Required frontmatter
+
+Every guide must include the following frontmatter at the top of the file:
+
+```mdx
+---
+title: 'How to [do something] with Prisma ORM'
+metaTitle: 'How to [do something] with Prisma ORM'
+metaDescription: 'Learn how to [do something] with Prisma ORM'
+sidebar_label: '[Concise Label]'
+image: '/img/guides/[guide-name]-cover.png'
+---
+```
+
+- `title`: Should be action-oriented and start with "How to"
+- `metaTitle`: Usually matches the title
+- `metaDescription`: A one-sentence summary starting with "Learn how to"
+- `sidebar_label`: A concise label for the sidebar navigation
+- `image`: A unique header image for social media sharing (coordinate with the design team)
+
+All frontmatter fields should be in sentence case, except for `image`.
+
+### Required sections
+
+1. **Introduction**
+ - Brief overview of what the guide covers
+ - What the reader will learn/accomplish
+ - Link to any example repositories or related resources
+
+2. **Prerequisites**
+ - Required software/tools with version numbers
+ - Required knowledge/experience
+ - Any necessary accounts or access
+
+3. **Main content sections**
+ - Numbered steps for procedural guides (e.g., "1. Set up the project")
+ - Clear hierarchy with H2 (`##`) for main sections
+ - H3 (`###`) for subsections
+ - Each step should build on previous steps
+
+4. **Next steps**
+ - What to do after completing the guide
+ - Related guides or documentation
+ - Links to additional resources
+ - Community resources (e.g., Discord)
+
+## Writing style and voice
+
+### General principles
+
+- Write in a clear, conversational tone
+- Use active voice and present tense
+- Address the reader directly using "you"
+- Use first person plural ("we") when guiding the reader through steps
+- Avoid jargon and explain technical terms
+- Be concise but thorough
+
+### Code examples
+
+- Include complete, runnable code examples
+- Use syntax highlighting with language specification
+- Include file paths in code block metadata
+- Use comments to explain complex parts
+- Show both the problem and solution when applicable
+
+Example:
+
+```typescript file=src/index.ts
+// Import required dependencies
+import { PrismaClient } from '@prisma/client'
+
+// Initialize Prisma Client
+const prisma = new PrismaClient()
+```
+
+### Formatting conventions
+
+- Use backticks for:
+ - File names: \`schema.prisma\`
+ - Directory names: \`prisma/\`
+ - Code elements: \`PrismaClient\`
+ - Commands: \`npx prisma generate\`
+- Use [admonitions](https://docusaurus.io/docs/markdown-features/admonitions) for important notes, warnings, tips, etc.:
+ ```mdx
+ :::note
+ Important information goes here
+ :::
+ ```
+- Use proper heading hierarchy (never skip levels)
+- Include line numbers in longer code blocks
+- Use tabbed content for alternative approaches
+
+## Examples from existing guides
+
+### Migration guide format
+
+Migration guides follow a specific pattern, as seen in guides like [Migrate from Sequelize](/guides/migrate-from-sequelize) and [Migrate from Mongoose](/guides/migrate-from-mongoose):
+
+1. Clear introduction explaining the migration path
+2. Prerequisites specific to both ORMs
+3. Step-by-step migration process
+4. Code comparison between ORMs
+5. Practical examples of common operations
+
+### Integration guide format
+
+Integration guides, like [Using Prisma ORM with Cloudflare D1](/guides/using-prisma-orm-with-cloudflare-d1), focus on:
+
+1. Setup and configuration
+2. Platform-specific considerations
+3. Step-by-step implementation
+4. Deployment instructions
+5. Platform-specific best practices
+
+## Best practices
+
+1. **Keep it focused**
+ - Each guide should cover one main topic
+ - Break complex topics into multiple guides
+ - Link to related guides instead of duplicating content
+
+2. **Show don't tell**
+ - Include practical, real-world examples
+ - Provide complete, working code samples
+ - Explain why certain approaches are recommended
+
+3. **Consider the context**
+ - Explain prerequisites clearly
+ - Don't assume prior knowledge
+ - Link to foundational concepts within or outside of our docs when needed
+
+4. **Maintain consistency**
+ - Follow the established guide structure
+ - Use consistent terminology
+ - Match the style of existing guides
+
+5. **Think about maintenance**
+ - Use version numbers where appropriate
+ - Avoid time-sensitive references
+ - Consider future updates when structuring content
+
+## Next steps
+
+After reading this guide, you can:
+
+- Start writing your own guide using the provided structure
+- Review existing guides for reference
+- Request a unique header image for your guide
+- Submit your guide for review
+
+For more information and updates:
+- [Prisma documentation style guide](/about/style-guide)
+- [Documentation components](/about/docs-components)
+- Join our [Discord community](https://discord.com/invite/prisma)
\ No newline at end of file
diff --git a/content/800-guides/600-migrate-from-sequelize.mdx b/content/800-guides/600-migrate-from-sequelize.mdx
new file mode 100644
index 0000000000..f71a3fab08
--- /dev/null
+++ b/content/800-guides/600-migrate-from-sequelize.mdx
@@ -0,0 +1,232 @@
+---
+title: 'How to migrate from Sequelize to Prisma ORM'
+metaTitle: 'How to migrate from Sequelize to Prisma ORM'
+metaDescription: 'Learn how to migrate from Sequelize to Prisma ORM'
+sidebar_label: 'Migrate from Sequelize'
+image: '/img/guides/migrate-from-sequelize-cover.png'
+---
+
+## Introduction
+
+This guide shows you how to migrate your application from Sequelize to Prisma ORM. We'll use an extended version of the [Sequelize Express example](https://github.com/sequelize/express-example) as a [sample project](https://github.com/prisma/migrate-from-sequelize-to-prisma) to demonstrate the migration steps.
+
+This migration guide uses PostgreSQL as the example database, but it equally applies to any other relational database that's [supported by Prisma ORM](/orm/reference/supported-databases). You can learn how Prisma ORM compares to Sequelize on the [Prisma ORM vs Sequelize](/orm/more/comparisons/prisma-and-sequelize) page.
+
+## Prerequisites
+
+Before starting this guide, make sure you have:
+
+- A Sequelize project you want to migrate
+- Node.js installed (version 18 or higher)
+- PostgreSQL or another supported database
+- Basic familiarity with Sequelize and Express.js
+
+## 1. Prepare for migration
+
+### 1.1. Understand the migration process
+
+The steps for migrating from Sequelize to Prisma ORM are always the same, no matter what kind of application or API layer you're building:
+
+1. Install the Prisma CLI
+2. Introspect your database
+3. Create a baseline migration
+4. Install Prisma Client
+5. Gradually replace your Sequelize queries with Prisma Client
+
+These steps apply whether you're building a REST API (e.g., with Express, Koa, or NestJS), a GraphQL API (e.g., with Apollo Server, TypeGraphQL, or Nexus), or any other kind of application that uses Sequelize for database access.
+
+### 1.2. Set up Prisma configuration
+
+Create a new Prisma schema file:
+
+```terminal
+npx prisma init
+```
+
+This command created a new directory called `prisma` with the following files for you:
+
+- `schema.prisma`: Your Prisma schema that specifies your database connection and models
+- `.env`: A [`dotenv`](https://github.com/motdotla/dotenv) to configure your database connection URL as an environment variable
+
+The Prisma schema currently looks as follows:
+
+```prisma file=prisma/schema.prisma showLineNumbers
+// This is your Prisma schema file,
+// learn more about it in the docs: https://pris.ly/d/prisma-schema
+
+datasource db {
+ provider = "postgresql"
+ url = env("DATABASE_URL")
+}
+
+generator client {
+ provider = "prisma-client-js"
+}
+```
+
+:::tip
+
+If you're using VS Code, be sure to install the [Prisma VS Code extension](https://marketplace.visualstudio.com/items?itemName=Prisma.prisma) for syntax highlighting, formatting, auto-completion and a lot more cool features.
+
+:::
+
+Update the `DATABASE_URL` in the `.env` file with your database connection string:
+
+```env
+DATABASE_URL="postgresql://USER:PASSWORD@HOST:PORT/DATABASE"
+```
+
+## 2. Migrate the database schema
+
+### 2.1. Introspect your database
+
+Run Prisma's introspection to create the Prisma schema from your existing database:
+
+```terminal
+npx prisma db pull
+```
+
+This will create a `schema.prisma` file with your database schema.
+
+### 2.2. Create a baseline migration
+
+To continue using Prisma Migrate to evolve your database schema, you will need to [baseline your database](/orm/prisma-migrate/getting-started).
+
+First, create a `migrations` directory and add a directory inside with your preferred name for the migration. In this example, we will use `0_init` as the migration name:
+
+```terminal
+mkdir -p prisma/migrations/0_init
+```
+
+Next, generate the migration file with `prisma migrate diff`. Use the following arguments:
+
+- `--from-empty`: assumes the data model you're migrating from is empty
+- `--to-schema-datamodel`: the current database state using the URL in the `datasource` block
+- `--script`: output a SQL script
+
+```terminal wrap
+npx prisma migrate diff --from-empty --to-schema-datamodel prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql
+npx prisma migrate resolve --applied 0_init
+```
+
+The command will mark `0_init` as applied by adding it to the `_prisma_migrations` table.
+
+You now have a baseline for your current database schema. To make further changes to your database schema, you can update your Prisma schema and use `prisma migrate dev` to apply the changes to your database.
+
+## 3. Update your application code
+
+### 3.1. Install Prisma Client
+
+As a next step, you can install Prisma Client in your project so that you can start replacing the database queries in your project that are currently made with Sequelize:
+
+```terminal
+npm install @prisma/client
+```
+
+After installing Prisma Client, you can generate the Prisma Client code:
+
+```terminal
+npx prisma generate
+```
+
+### 3.2. Replace Sequelize queries
+
+In this section, we'll show a few sample queries that are being migrated from Sequelize to Prisma Client based on the example routes from the sample REST API project. For a comprehensive overview of how the Prisma Client API differs from Sequelize, check out the [API comparison](/orm/more/comparisons/prisma-and-sequelize#api-comparison) page.
+
+
+
+
+
+```typescript
+// Find one
+const user = await User.findOne({
+ where: { id: 1 }
+});
+
+// Create
+const user = await User.create({
+ email: 'alice@prisma.io',
+ name: 'Alice'
+});
+
+// Update
+await User.update({ name: 'New name' }, {
+ where: { id: 1 }
+});
+
+// Delete
+await User.destroy({
+ where: { id: 1 }
+});
+```
+
+
+
+
+
+```typescript
+// Find one
+const user = await prisma.user.findUnique({
+ where: { id: 1 }
+});
+
+// Create
+const user = await prisma.user.create({
+ data: {
+ email: 'alice@prisma.io',
+ name: 'Alice'
+ }
+});
+
+// Update
+await prisma.user.update({
+ where: { id: 1 },
+ data: { name: 'New name' }
+});
+
+// Delete
+await prisma.user.delete({
+ where: { id: 1 }
+});
+```
+
+
+
+
+
+### 3.3. Update your controllers
+
+Update your Express controllers to use Prisma Client. For example, here's how to update a user controller:
+
+```typescript
+import { prisma } from '../client'
+
+export class UserController {
+ async create(req: Request, res: Response) {
+ const { email, name } = req.body
+
+ const result = await prisma.user.create({
+ data: {
+ email,
+ name,
+ },
+ })
+
+ return res.json(result)
+ }
+}
+```
+
+## Next steps
+
+Now that you've migrated to Prisma ORM, you can:
+
+- Add more complex queries using Prisma's powerful query API
+- Set up Prisma Studio for database management
+- Implement database monitoring
+- Add automated tests using Prisma's testing utilities
+
+For more information and updates:
+- [Prisma ORM documentation](/orm)
+- [Prisma Client API reference](/orm/prisma-client)
+- Join our [Discord community](https://discord.com/invite/prisma)
diff --git a/content/800-guides/700-migrate-from-mongoose.mdx b/content/800-guides/700-migrate-from-mongoose.mdx
new file mode 100644
index 0000000000..fd68b3600a
--- /dev/null
+++ b/content/800-guides/700-migrate-from-mongoose.mdx
@@ -0,0 +1,343 @@
+---
+title: 'How to migrate from Mongoose to Prisma ORM'
+metaTitle: 'How to migrate from Mongoose to Prisma ORM'
+metaDescription: 'Learn how to migrate from Mongoose to Prisma ORM'
+sidebar_label: 'Migrate from Mongoose'
+image: '/img/guides/migrate-from-mongoose-cover.png'
+---
+
+## Introduction
+
+This guide shows you how to migrate your application from Mongoose to Prisma ORM. We'll use an extended version of the [Mongoose Express example](https://github.com/Automattic/mongoose/tree/master/examples/express) as a [sample project](https://github.com/prisma/migrate-from-mongoose-to-prisma) to demonstrate the migration steps.
+
+You can learn how Prisma ORM compares to Mongoose on the [Prisma ORM vs Mongoose](/orm/more/comparisons/prisma-and-mongoose) page.
+
+## Prerequisites
+
+Before starting this guide, make sure you have:
+
+- A Mongoose project you want to migrate
+- Node.js installed (version 18 or higher)
+- MongoDB database
+- Basic familiarity with Mongoose and Express.js
+
+## 1. Prepare for migration
+
+### 1.1. Understand the migration process
+
+The steps for migrating from Mongoose to Prisma ORM are always the same, no matter what kind of application or API layer you're building:
+
+1. Install the Prisma CLI
+2. Introspect your database
+3. Install and generate Prisma Client
+4. Gradually replace your Mongoose queries with Prisma Client
+
+These steps apply whether you're building a REST API (e.g., with Express, Koa, or NestJS), a GraphQL API (e.g., with Apollo Server, TypeGraphQL, or Nexus), or any other kind of application that uses Mongoose for database access.
+
+### 1.2. Set up Prisma configuration
+
+Create a new Prisma schema file:
+
+```terminal
+npx prisma init --datasource-provider mongodb
+```
+
+This command creates:
+
+- A new directory called `prisma` that contains a `schema.prisma` file; your Prisma schema specifies your database connection and models
+- `.env`: A [`dotenv`](https://github.com/motdotla/dotenv) file at the root of your project (if it doesn't already exist), used to configure your database connection URL as an environment variable
+
+The Prisma schema currently looks as follows:
+
+```prisma file=prisma/schema.prisma showLineNumbers
+// This is your Prisma schema file,
+// learn more about it in the docs: https://pris.ly/d/prisma-schema
+
+datasource db {
+ provider = "mongodb"
+ url = env("DATABASE_URL")
+}
+
+generator client {
+ provider = "prisma-client-js"
+}
+```
+
+
+:::tip
+
+For an optimal development experience when working with Prisma ORM, refer to [editor setup](/orm/more/development-environment/editor-setup) to learn about syntax highlighting, formatting, auto-completion, and many more cool features.
+
+:::
+
+Update the `DATABASE_URL` in the `.env` file with your MongoDB connection string:
+
+```env
+DATABASE_URL="mongodb://USER:PASSWORD@HOST:PORT/DATABASE"
+```
+
+## 2. Migrate the database schema
+
+### 2.1. Introspect your database
+
+:::warning
+
+MongoDB is a _schemaless_ database. To incrementally adopt Prisma ORM in your project, ensure your database is populated with sample data. Prisma ORM introspects a MongoDB schema by sampling data stored and inferring the schema from the data in the database.
+
+:::
+
+Run Prisma's introspection to create the Prisma schema from your existing database:
+
+```terminal
+npx prisma db pull
+```
+
+This will create a `schema.prisma` file with your database schema.
+
+```prisma file=prisma/schema.prisma showLineNumbers
+type UsersProfile {
+ bio String
+}
+
+model categories {
+ id String @id @default(auto()) @map("_id") @db.ObjectId
+ v Int @map("__v")
+ name String
+}
+
+model posts {
+ id String @id @default(auto()) @map("_id") @db.ObjectId
+ v Int @map("__v")
+ author String @db.ObjectId
+ categories String[] @db.ObjectId
+ content String
+ published Boolean
+ title String
+}
+
+model users {
+ id String @id @default(auto()) @map("_id") @db.ObjectId
+ v Int @map("__v")
+ email String @unique(map: "email_1")
+ name String
+ profile UsersProfile?
+}
+```
+
+### 2.2. Update relations
+
+MongoDB doesn't support relations between different collections. However, you can create references between documents using the [`ObjectId`](/orm/overview/databases/mongodb#using-objectid) field type or from one document to many using an array of `ObjectIds` in the collection. The reference will store id(s) of the related document(s). You can use the `populate()` method that Mongoose provides to populate the reference with the data of the related document.
+
+Update the 1-n relationship between `posts` \<-> `users` as follows:
+
+- Rename the existing `author` reference in the `posts` model to `authorId` and add the `@map("author")` attribute
+- Add the `author` relation field in the `posts` model and it's `@relation` attribute specifying the `fields` and `references`
+- Add the `posts` relation in the `users` model
+
+Your schema should now look like this:
+
+```prisma file=schema.prisma
+type UsersProfile {
+ bio String
+}
+
+model categories {
+ id String @id @default(auto()) @map("_id") @db.ObjectId
+ v Int @map("__v")
+ name String
+}
+
+model posts {
+ id String @id @default(auto()) @map("_id") @db.ObjectId
+ title String
+ content String
+ published Boolean
+ v Int @map("__v")
+ //delete-next-line
+ author String @db.ObjectId
+ //add-start
+ author users @relation(fields: [authorId], references: [id])
+ authorId String @map("author") @db.ObjectId
+ //add-end
+
+ categories String[] @db.ObjectId
+}
+
+model users {
+ id String @id @default(auto()) @map("_id") @db.ObjectId
+ v Int @map("__v")
+ email String @unique(map: "email_1")
+ name String
+ profile UsersProfile?
+ //add-next-line
+ posts posts[]
+}
+```
+
+Then, update the m-n between `posts` \<-\> `categories` references as follows:
+
+- Rename the `categories` field to `categoryIds` and map it using `@map("categories")` in the `posts` model
+- Add a new `categories` relation field in the `posts` model
+- Add the `postIds` scalar list field in the `categories` model
+- Add the `posts` relation in the `categories` model
+- Add a [relation scalar](/orm/prisma-schema/data-model/relations#annotated-relation-fields) on both models
+- Add the `@relation` attribute specifying the `fields` and `references` arguments on both sides
+
+Your schema should now look like this:
+
+```prisma file=schema.prisma
+type UsersProfile {
+ bio String
+}
+
+model categories {
+ id String @id @default(auto()) @map("_id") @db.ObjectId
+ v Int @map("__v")
+ name String
+ //add-start
+ posts posts[] @relation(fields: [postIds], references: [id])
+ postIds String[] @db.ObjectId
+ //add-end
+}
+
+model posts {
+ id String @id @default(auto()) @map("_id") @db.ObjectId
+ title String
+ content String
+ published Boolean
+ v Int @map("__v")
+
+ author users @relation(fields: [authorId], references: [id])
+ authorId String @map("author") @db.ObjectId
+
+ //delete-next-line
+ categories String[] @db.ObjectId
+ //add-start
+ categories categories[] @relation(fields: [categoryIds], references: [id])
+ categoryIds String[] @map("categories") @db.ObjectId
+ //add-end
+}
+
+model users {
+ id String @id @default(auto()) @map("_id") @db.ObjectId
+ v Int @map("__v")
+ email String @unique(map: "email_1")
+ name String
+ profile UsersProfile?
+ posts posts[]
+}
+```
+
+## 3. Update your application code
+
+### 3.1. Install Prisma Client
+
+Install the Prisma Client package:
+
+```terminal
+npm install @prisma/client
+```
+
+After installing the Prisma Client package, generate Prisma Client:
+
+```terminal
+npx prisma generate
+```
+
+### 3.2. Replace Mongoose queries
+
+Start replacing your Mongoose queries with Prisma Client. Here's an example of how to convert some common queries:
+
+
+
+
+
+```typescript
+// Find one
+const user = await User.findById(id);
+
+// Create
+const user = await User.create({
+ email: 'alice@prisma.io',
+ name: 'Alice'
+});
+
+// Update
+await User.findByIdAndUpdate(id, {
+ name: 'New name'
+});
+
+// Delete
+await User.findByIdAndDelete(id);
+```
+
+
+
+
+
+```typescript
+// Find one
+const user = await prisma.user.findUnique({
+ where: { id }
+});
+
+// Create
+const user = await prisma.user.create({
+ data: {
+ email: 'alice@prisma.io',
+ name: 'Alice'
+ }
+});
+
+// Update
+await prisma.user.update({
+ where: { id },
+ data: { name: 'New name' }
+});
+
+// Delete
+await prisma.user.delete({
+ where: { id }
+});
+```
+
+
+
+
+
+### 3.3. Update your controllers
+
+Update your Express controllers to use Prisma Client. For example, here's how to update a user controller:
+
+```typescript
+import { prisma } from '../client'
+
+export class UserController {
+ async create(req: Request, res: Response) {
+ const { email, name } = req.body
+
+ const result = await prisma.user.create({
+ data: {
+ email,
+ name,
+ },
+ })
+
+ return res.json(result)
+ }
+}
+```
+
+## Next steps
+
+Now that you've migrated to Prisma ORM, you can:
+
+- Add more complex queries using Prisma's powerful query API
+- Set up Prisma Studio for database management
+- Implement database monitoring
+- Add automated tests using Prisma's testing utilities
+
+For more information and updates:
+- [Prisma ORM documentation](/orm)
+- [Prisma Client API reference](/orm/prisma-client)
+- Join our [Discord community](https://discord.com/invite/prisma)
\ No newline at end of file
diff --git a/content/200-orm/800-more/450-migrating-to-prisma/04-migrate-from-drizzle.mdx b/content/800-guides/800-migrate-from-drizzle.mdx
similarity index 93%
rename from content/200-orm/800-more/450-migrating-to-prisma/04-migrate-from-drizzle.mdx
rename to content/800-guides/800-migrate-from-drizzle.mdx
index bf9dde83cf..24cc2bc619 100644
--- a/content/200-orm/800-more/450-migrating-to-prisma/04-migrate-from-drizzle.mdx
+++ b/content/800-guides/800-migrate-from-drizzle.mdx
@@ -1,10 +1,25 @@
---
-title: "Migrate from Drizzle"
-metaTitle: "How to migrate from Drizzle to Prisma ORM"
-metaDescription: "Learn how to migrate from Drizzle to Prisma ORM"
+title: 'How to migrate from Drizzle to Prisma ORM'
+metaTitle: 'How to migrate from Drizzle to Prisma ORM'
+metaDescription: 'Learn how to migrate from Drizzle to Prisma ORM'
+sidebar_label: 'Migrate from Drizzle'
+image: '/img/guides/migrate-from-drizzle-cover.png'
---
-This guide describes how to migrate from Drizzle to Prisma ORM. It uses a sample project based off of the [Drizzle Next.js example](https://orm.drizzle.team/docs/tutorials/drizzle-nextjs-neon) as a [sample project](https://github.com/prisma/migrate-from-drizzle-to-prisma) to demonstrate the migration steps. You can find the example used for this guide on [GitHub](https://github.com/prisma/migrate-from-drizzle-to-prisma).
+## Introduction
+
+This guide shows you how to migrate your application from Drizzle to Prisma ORM. We'll use a sample project based off of the [Drizzle Next.js example](https://orm.drizzle.team/docs/tutorials/drizzle-nextjs-neon) to demonstrate the migration steps. You can find the example used for this guide on [GitHub](https://github.com/prisma/migrate-from-drizzle-to-prisma).
+
+You can learn how Prisma ORM compares to Drizzle on the [Prisma ORM vs Drizzle](/orm/more/comparisons/prisma-and-drizzle) page.
+
+## Prerequisites
+
+Before starting this guide, make sure you have:
+
+- A Drizzle project you want to migrate
+- Node.js installed (version 16 or higher)
+- PostgreSQL or another supported database
+- Basic familiarity with Drizzle and Next.js
:::note
diff --git a/content/800-guides/900-using-prisma-orm-with-cloudflare-d1.mdx b/content/800-guides/900-using-prisma-orm-with-cloudflare-d1.mdx
new file mode 100644
index 0000000000..4d8dcfa618
--- /dev/null
+++ b/content/800-guides/900-using-prisma-orm-with-cloudflare-d1.mdx
@@ -0,0 +1,216 @@
+---
+title: 'How to use Prisma ORM with Cloudflare D1'
+metaTitle: 'How to use Prisma ORM with Cloudflare D1'
+metaDescription: 'Learn how to use Prisma ORM with Cloudflare D1'
+sidebar_label: 'Use with Cloudflare D1'
+image: '/img/guides/prisma-d1-setup-cover.png'
+---
+
+## Introduction
+
+This guide shows you how to use Prisma ORM with Cloudflare D1, a serverless SQL database that runs on Cloudflare's edge network. You'll learn how to set up Prisma ORM with D1, handle migrations, and deploy your application to Cloudflare Workers. You can find a [deployment-ready example on GitHub](https://github.com/prisma/prisma-examples/blob/latest/deployment-platforms/edge/cloudflare-workers/with-d1).
+
+## Prerequisites
+
+Before starting this guide, make sure you have:
+
+- A Cloudflare account
+- Node.js installed (version 16 or higher)
+- Wrangler CLI installed (version 3.39.0 or higher)
+- Basic familiarity with Cloudflare Workers and D1
+
+## 1. Configure Prisma schema
+
+In your Prisma schema, add the `driverAdapters` Preview feature to the `generator` block and set the `provider` of the `datasource` to `sqlite`. If you just bootstrapped the Prisma schema with `prisma init`, also be sure to add the following `User` model to it:
+
+```prisma file=schema.prisma
+generator client {
+ provider = "prisma-client-js"
+ previewFeatures = ["driverAdapters"]
+}
+
+datasource db {
+ provider = "sqlite"
+ url = env("DATABASE_URL")
+}
+
+model User {
+ id Int @id @default(autoincrement())
+ email String @unique
+ name String?
+}
+```
+
+## 2. Install dependencies
+
+Next, install the required packages:
+
+```terminal
+npm install @prisma/adapter-d1
+```
+
+Also, be sure to use a version of the Wrangler CLI that's above [`wrangler@^3.39.0`](https://github.com/cloudflare/workers-sdk/releases/tag/wrangler%403.39.0), otherwise the `--remote` flag that's used in the next sections won't be available.
+
+## 3. Set up D1 database connection
+
+To connect your Workers with the D1 instance, add the following binding to your `wrangler.toml`:
+
+```toml file=wrangler.toml
+name = "prisma-cloudflare-worker-example"
+main = "src/index.ts"
+compatibility_date = "2024-03-20"
+compatibility_flags = ["nodejs_compat"]
+
+[[d1_databases]]
+binding = "DB" # i.e. available in your Worker on env.DB
+database_name = "__YOUR_D1_DATABASE_NAME__" # to be replaced
+database_id = "__YOUR_D1_DATABASE_ID__" # to be replaced
+```
+
+Note that `__YOUR_D1_DATABASE_NAME__` and `__YOUR_D1_DATABASE_ID__` in the snippet above are placeholders that should be replaced with the database name and ID of your own D1 instance.
+
+If you weren't able to grab this ID from the terminal output, you can also find it in the Cloudflare Dashboard or by running `npx wrangler d1 list` and `npx wrangler d1 info __YOUR_D1_DATABASE_NAME__` in your terminal.
+
+## 4. Set up database migrations
+
+Create and apply migrations using D1's [migration system](https://developers.cloudflare.com/d1/reference/migrations/):
+
+```terminal
+# Create migration directory and file
+npx wrangler d1 migrations create __YOUR_D1_DATABASE_NAME__ create_user_table
+```
+
+Replace `__YOUR_D1_DATABASE_NAME__` with the name of your database again and, when prompted, confirm that you want to create the `migrations` directory. After having run this command, there should be a new folder called `migrations` with a file called `0001_create_user_table.sql` inside of it.
+
+You can now generate the required SQL statement for creating a `User` table that can be mapped to the `User` model in your the Prisma schema as follows:
+
+```terminal
+# Generate SQL using Prisma Migrate
+npx prisma migrate diff --from-empty --to-schema-datamodel ./prisma/schema.prisma --script --output migrations/0001_create_user_table.sql
+```
+
+Note that the resulting SQL statement is stored in a file in the `migrations` directory called `0001_create_user_table.sql` which looks as follows:
+
+```sql file=migrations/0001_create_user_table.sql no-copy
+-- CreateTable
+CREATE TABLE "User" (
+ "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
+ "email" TEXT NOT NULL,
+ "name" TEXT
+);
+
+-- CreateIndex
+CREATE UNIQUE INDEX "User_email_key" ON "User"("email");
+```
+
+You now need to use the [`wrangler d1 migrations apply`](https://developers.cloudflare.com/workers/wrangler/commands/#migrations-apply) command to send this SQL statement to D1. Note that this command accepts two options:
+
+- `--local`: Executes the statement against a _local_ version of D1. This local version of D1 is a SQLite database file that'll be located in your project. This approach is useful, when you want to develop and test your Worker on your local machine. Learn more in the [Cloudflare docs](https://developers.cloudflare.com/d1/build-with-d1/local-development/).
+- `--remote`: Executes the statement against your _remote_ version of D1. This version is used by your _deployed_ Cloudflare Workers. Learn more in the [Cloudflare docs](https://developers.cloudflare.com/d1/build-with-d1/remote-development/).
+
+In this tutorial, you'll do both: test the Worker locally _and_ deploy it afterwards. So, you need to run both commands. Open your terminal and paste the following commands:
+
+```terminal
+# For the local database
+npx wrangler d1 migrations apply __YOUR_D1_DATABASE_NAME__ --local
+
+# For the remote database
+npx wrangler d1 migrations apply __YOUR_D1_DATABASE_NAME__ --remote
+```
+
+As before, you need to replace `__YOUR_D1_DATABASE_NAME__` with the name of your D1 database.
+
+Let's also create some dummy data that we can query once the Worker is running. This time, you'll run the SQL statement without storing it in a file:
+
+```terminal
+# For the local database
+npx wrangler d1 execute __YOUR_D1_DATABASE_NAME__ --command "INSERT INTO \"User\" (\"email\", \"name\") VALUES
+('jane@prisma.io', 'Jane Doe (Local)');" --local
+
+# For the remote database
+npx wrangler d1 execute __YOUR_D1_DATABASE_NAME__ --command "INSERT INTO \"User\" (\"email\", \"name\") VALUES
+('jane@prisma.io', 'Jane Doe (Remote)');" --remote
+```
+
+## 5. Implement the Worker
+
+Before adding a Prisma Client query to your Worker, you need to generate Prisma Client with the following command:
+
+```
+npx prisma generate
+```
+
+In order to query your database from the Worker using Prisma ORM, you need to:
+
+1. Add the `DB` binding to the `Env` interface. (Alternatively, you can run [`npx wrangler types`](https://developers.cloudflare.com/workers/wrangler/commands/#types) to generate the `Env` type from the binding in a separate file called `worker-configuration.d.ts`.)
+2. Instantiate `PrismaClient` using the `PrismaD1` driver adapter.
+3. Send a query using Prisma Client and return the result.
+
+Open `src/index.ts` and replace the entire content with the following:
+
+```typescript file=src/index.ts
+import { PrismaClient } from '@prisma/client'
+import { PrismaD1 } from '@prisma/adapter-d1'
+
+export interface Env {
+ DB: D1Database
+}
+
+export default {
+ async fetch(
+ request: Request,
+ env: Env,
+ ctx: ExecutionContext
+ ): Promise {
+ const adapter = new PrismaD1(env.DB)
+ const prisma = new PrismaClient({ adapter })
+
+ const users = await prisma.user.findMany()
+ const result = JSON.stringify(users)
+ return new Response(result)
+ },
+}
+```
+
+## 6. Run the Worker locally
+
+With the database query in place and Prisma Client generated, you can go ahead and run the Worker locally:
+
+```
+npm run dev
+```
+
+Now you can open your browser at [`http://localhost:8787`](http://localhost:8787/) to see the result of the database query:
+
+```js no-copy
+;[{ id: 1, email: 'jane@prisma.io', name: 'Jane Doe (Local)' }]
+```
+
+## 7. Set the `DATABASE_URL` environment variable and deploy the Worker
+
+To deploy the Worker, run the the following command:
+
+```
+npm run deploy
+```
+
+Your deployed Worker is accessible via `https://prisma-d1-example.USERNAME.workers.dev`. If you navigate your browser to that URL, you should see the following data that's queried from your remote D1 database:
+
+```js no-copy
+;[{ id: 1, email: 'jane@prisma.io', name: 'Jane Doe (Remote)' }]
+```
+
+## Next steps
+
+Now that you've set up Prisma ORM with Cloudflare D1, you can:
+
+- Add more complex queries using Prisma's powerful query API
+- Set up Prisma Studio for database management
+- Implement database monitoring
+- Add automated tests
+
+For more information and updates:
+- [Prisma ORM documentation](/orm)
+- [Prisma Client API reference](/orm/prisma-client)
+- [Cloudflare D1 documentation](https://developers.cloudflare.com/d1)
+- Join our [Discord community](https://discord.com/invite/prisma)
\ No newline at end of file
diff --git a/content/800-guides/index.mdx b/content/800-guides/index.mdx
new file mode 100644
index 0000000000..946e979769
--- /dev/null
+++ b/content/800-guides/index.mdx
@@ -0,0 +1,25 @@
+---
+title: 'Guides'
+metaTitle: 'Prisma Guides'
+metaDescription: 'A collection of guides for various tasks and workflows.'
+sidebar_label: 'Guides'
+sidebar_position: 0
+tags:
+ - guides
+ - tutorials
+ - workflows
+ - database
+ - migration
+ - testing
+ - deployment
+ - optimization
+ - best-practices
+---
+
+# Guides
+
+Welcome to the Guides section! Here you will find various guides to help you with different tasks and workflows. Learn how to include Prisma ORM in your project, or integrate Prisma ORM with various services and libraries.
+
+## Available Guides
+
+
diff --git a/docusaurus.config.ts b/docusaurus.config.ts
index 71805d2b03..6b1b535fa6 100644
--- a/docusaurus.config.ts
+++ b/docusaurus.config.ts
@@ -215,6 +215,12 @@ const config: Config = {
},
],
},
+ {
+ type: "docSidebar",
+ sidebarId: "guidesSidebar",
+ className: "teal",
+ label: "Guides",
+ },
{
to: "https://www.github.com/prisma/prisma-examples",
external: true,
diff --git a/sidebars.ts b/sidebars.ts
index d1adae322f..59450c1482 100644
--- a/sidebars.ts
+++ b/sidebars.ts
@@ -356,6 +356,22 @@ const sidebars: SidebarsConfig = {
items: [{ type: "autogenerated", dirName: "600-about" }],
},
],
+ guidesSidebar: [
+ {
+ type: "category",
+ label: "Guides",
+ collapsible: false,
+ collapsed: false,
+ link: {
+ type: "doc",
+ id: "guides/index",
+ },
+ className: "firstTitle",
+ items: [
+ { type: "autogenerated", dirName: "800-guides" },
+ ],
+ },
+ ],
};
export default sidebars;
diff --git a/src/data/indexData.ts b/src/data/indexData.ts
index d4f3a9abe1..fc1c58623f 100644
--- a/src/data/indexData.ts
+++ b/src/data/indexData.ts
@@ -118,9 +118,9 @@ export const ORMGeneralLinkData = [
icon: "fa-solid fa-arrow-right-arrow-left",
},
{
- title: `Adopting Prisma ORM`,
- description: "Migrate to Prisma ORM from other ORMs.",
- url: "/orm/more/migrating-to-prisma",
+ title: `Advanced queries`,
+ description: "Learn how to perform advanced queries with raw SQL in Prisma ORM.",
+ url: "/orm/prisma-client/using-raw-sql",
icon: "fa-solid fa-download",
},
{
@@ -147,9 +147,9 @@ export const GeneralLinks_Build = [
icon: "fa-solid fa-arrow-right-arrow-left",
},
{
- title: `Adopting Prisma ORM`,
- description: "Migrate to Prisma ORM from other ORMs.",
- url: "/orm/more/migrating-to-prisma",
+ title: `Advanced queries`,
+ description: "Learn how to perform advanced queries with raw SQL in Prisma ORM.",
+ url: "/orm/prisma-client/using-raw-sql",
icon: "fa-solid fa-download",
},
{
diff --git a/src/theme/DocCard/index.tsx b/src/theme/DocCard/index.tsx
index 26afe0fc9f..34986b20ca 100644
--- a/src/theme/DocCard/index.tsx
+++ b/src/theme/DocCard/index.tsx
@@ -1,54 +1,82 @@
-import React from "react";
+import React, { type ReactNode } from "react";
import clsx from "clsx";
import Link from "@docusaurus/Link";
-import { findFirstSidebarItemLink, useDocById } from "@docusaurus/plugin-content-docs/client";
+import { useDocById, findFirstSidebarItemLink } from "@docusaurus/plugin-content-docs/client";
+import { usePluralForm } from "@docusaurus/theme-common";
import isInternalUrl from "@docusaurus/isInternalUrl";
import { translate } from "@docusaurus/Translate";
+
+import type { Props } from "@theme/DocCard";
import Heading from "@theme/Heading";
+import type { PropSidebarItemCategory, PropSidebarItemLink } from "@docusaurus/plugin-content-docs";
+
import styles from "./styles.module.scss";
-function CardContainer({ href, children }) {
+
+function useCategoryItemsPlural() {
+ const { selectMessage } = usePluralForm();
+ return (count: number) =>
+ selectMessage(
+ count,
+ translate(
+ {
+ message: "1 item|{count} items",
+ id: "theme.docs.DocCard.categoryDescription.plurals",
+ description:
+ "The default description for a category card in the generated index about how many items this category includes",
+ },
+ { count }
+ )
+ );
+}
+
+function CardContainer({ href, children }: { href: string; children: ReactNode }): JSX.Element {
return (
{children}
);
}
-function CardLayout({ href, icon, title, description }) {
+
+function CardLayout({
+ href,
+ icon,
+ title,
+ description,
+}: {
+ href: string;
+ icon: ReactNode;
+ title: string;
+ description?: string;
+}): JSX.Element {
return (
-
+
{title}
+ {description && (
+
+ {description}
+
+ )}
);
}
-function CardCategory({ item }) {
+
+function CardCategory({ item }: { item: PropSidebarItemCategory }): JSX.Element | null {
const href = findFirstSidebarItemLink(item);
+ const categoryItemsPlural = useCategoryItemsPlural();
+
// Unexpected: categories that don't have a link have been filtered upfront
if (!href) {
return null;
}
+
return (
-
+
);
}
-function CardLink({ item }) {
+
+function CardLink({ item }: { item: PropSidebarItemLink }): JSX.Element {
const icon = isInternalUrl(item.href) ? "📄️" : "🔗";
const doc = useDocById(item.docId ?? undefined);
return (
@@ -60,7 +88,8 @@ function CardLink({ item }) {
/>
);
}
-export default function DocCard({ item }) {
+
+export default function DocCard({ item }: Props): JSX.Element {
switch (item.type) {
case "link":
return ;
diff --git a/src/theme/DocCardList/index.tsx b/src/theme/DocCardList/index.tsx
index da6e72d209..83fad7b2e6 100644
--- a/src/theme/DocCardList/index.tsx
+++ b/src/theme/DocCardList/index.tsx
@@ -1,16 +1,19 @@
import React, { useEffect, useState } from "react";
import clsx from "clsx";
-import { useCurrentSidebarCategory, filterDocCardListItems } from "@docusaurus/theme-common";
-import DocCard from "../DocCard";
-import { useLocation } from "@docusaurus/router";
-import styles from "../DocCard/styles.module.scss";
-function DocCardListForCurrentSidebarCategory({ className }) {
+import {
+ useCurrentSidebarCategory,
+ filterDocCardListItems,
+} from "@docusaurus/plugin-content-docs/client";
+import DocCard from "@theme/DocCard";
+import type { Props } from "@theme/DocCardList";
+
+function DocCardListForCurrentSidebarCategory({ className }: Props) {
const category = useCurrentSidebarCategory();
return ;
}
-export default function DocCardList(props) {
+
+export default function DocCardList(props: Props): JSX.Element {
const { items, className } = props;
- const location = useLocation();
if (!items) {
return ;
}
@@ -21,7 +24,7 @@ export default function DocCardList(props) {
return (
{filteredItems.map((item, index) => (
-
+
))}
diff --git a/src/theme/MDXComponents.tsx b/src/theme/MDXComponents.tsx
index 2798d13834..b685ca1b40 100644
--- a/src/theme/MDXComponents.tsx
+++ b/src/theme/MDXComponents.tsx
@@ -5,9 +5,9 @@ import type { ComponentProps } from "react";
import MDXComponents from "@theme-original/MDXComponents";
// Import components we'd like to use across Docs
-import Subsections from "./DocCardList"; // DocCardList renamed to Subsections for backwards compat
+import DocCardList from "./DocCardList";
import Admonition from "@theme/Admonition";
-import TabbedContent from "./Tabs"; // Tabs renamed to TabbedContent for backwards compat
+import Tabs from "./Tabs"; // Tabs renamed to TabbedContent for backwards compat
import TabItem from "@theme/TabItem";
import BrowserOnly from "@docusaurus/BrowserOnly";
import Link from "@docusaurus/Link";
@@ -180,18 +180,24 @@ const Image: React.FC>> = ({ ...pr
export default {
// Re-use the default mapping
...MDXComponents,
- Subsections,
+ Subsections: DocCardList, // DocCardList renamed to Subsections for backwards compat
+ DocCardList,
Admonition,
- TabbedContent,
- details: CollapseBox,
+ TabbedContent: Tabs, // Tabs renamed to TabbedContent for backwards compat
+ Tabs,
TabItem,
+ details: CollapseBox,
a: StyledLink,
Link: DocsLink,
img: Image,
TopBlock,
CodeWithResult,
SwitchTech,
- table: (p: any) =>
{p.children}
,
+ table: (p: any) => (
+
+
{p.children}
+
+ ),
ParallelBlocks,
ButtonLink,
Button,
diff --git a/static/_redirects b/static/_redirects
index d14688faf3..feccb6b443 100644
--- a/static/_redirects
+++ b/static/_redirects
@@ -495,9 +495,10 @@
/guides/other/advanced-database-tasks/data-validation /docs/orm/prisma-client/queries/custom-validation
/guides/other/advanced-database-tasks /docs/orm
/guides/other /docs/orm
-/guides /docs/orm
/guides/upgrade-guides/upgrade-from-prisma-1/schema-incompatibilities-postgresql /docs/orm/more/upgrade-guides/upgrade-from-prisma-1/schema-incompatibilities-postgresql
/guides/upgrade-guides/upgrade-from-prisma-1/upgrading-the-prisma-layer-postgresql /docs/orm/more/upgrade-guides/upgrade-from-prisma-1/upgrading-the-prisma-layer-postgresql
+/guides/upgrade-guides/upgrade-from-prisma-1/schema-incompatibilities-mysql /docs/orm/more/upgrade-guides/upgrade-from-prisma-1/schema-incompatibilities-mysql
+/guides/upgrade-guides/upgrade-from-prisma-1/upgrading-the-prisma-layer-mysql /docs/orm/more/upgrade-guides/upgrade-from-prisma-1/upgrading-the-prisma-layer-mysql
/reference/api-reference /docs/orm/reference
/reference/database-reference /docs/orm/reference
/data-platform /docs/platform
@@ -506,8 +507,6 @@
/about/prisma/faq /docs/support
/about/prisma/limitations /docs/orm/prisma-schema/data-model/models#limitations
/about/prisma /docs/about
-/guides/upgrade-guides/upgrade-from-prisma-1/schema-incompatibilities-mysql /docs/orm/more/upgrade-guides/upgrade-from-prisma-1/schema-incompatibilities-mysql
-/guides/upgrade-guides/upgrade-from-prisma-1/upgrading-the-prisma-layer-mysql /docs/orm/more/upgrade-guides/upgrade-from-prisma-1/upgrading-the-prisma-layer-mysql
/concepts/overview/prisma-in-your-stack/graphql /docs/orm/overview/prisma-in-your-stack/graphql
/concepts/overview/prisma-in-your-stack/rest /docs/orm/overview/prisma-in-your-stack/rest
/accelerate/concepts /docs/accelerate
@@ -538,6 +537,11 @@
/accelerate/what-is-accelerate /docs/accelerate/
/pulse/what-is-pulse /docs/pulse/
/accelerate/limitations /docs/accelerate/known-limitations
+/orm/more/migrating-to-prisma /docs/guides
+/orm/more/migrating-to-prisma/migrate-from-typeorm /docs/guides/migrate-from-typeorm
+/orm/more/migrating-to-prisma/migrate-from-sequelize /docs/guides/migrate-from-sequelize
+/orm/more/migrating-to-prisma/migrate-from-mongoose /docs/guides/migrate-from-mongoose
+/orm/more/migrating-to-prisma/migrate-from-drizzle /docs/guides/migrate-from-drizzle
/getting-started/quickstart /docs/getting-started/quickstart-sqlite
# move help articles up a level
diff --git a/static/img/guides/data-migration-cover.png b/static/img/guides/data-migration-cover.png
new file mode 100644
index 0000000000..4ed66fe48e
Binary files /dev/null and b/static/img/guides/data-migration-cover.png differ
diff --git a/static/img/guides/migrate-from-drizzle-cover.png b/static/img/guides/migrate-from-drizzle-cover.png
new file mode 100644
index 0000000000..6021025373
Binary files /dev/null and b/static/img/guides/migrate-from-drizzle-cover.png differ
diff --git a/static/img/guides/migrate-from-mongoose-cover.png b/static/img/guides/migrate-from-mongoose-cover.png
new file mode 100644
index 0000000000..985c51ab81
Binary files /dev/null and b/static/img/guides/migrate-from-mongoose-cover.png differ
diff --git a/static/img/guides/migrate-from-sequelize-cover.png b/static/img/guides/migrate-from-sequelize-cover.png
new file mode 100644
index 0000000000..edbf09440b
Binary files /dev/null and b/static/img/guides/migrate-from-sequelize-cover.png differ
diff --git a/static/img/guides/migrate-from-typeorm-cover.png b/static/img/guides/migrate-from-typeorm-cover.png
new file mode 100644
index 0000000000..71f0ff8ba8
Binary files /dev/null and b/static/img/guides/migrate-from-typeorm-cover.png differ
diff --git a/static/img/guides/migrate-team-dev.png b/static/img/guides/migrate-team-dev.png
new file mode 100644
index 0000000000..c350446336
Binary files /dev/null and b/static/img/guides/migrate-team-dev.png differ
diff --git a/static/img/guides/migration-history.png b/static/img/guides/migration-history.png
new file mode 100644
index 0000000000..7fedefbd2b
Binary files /dev/null and b/static/img/guides/migration-history.png differ
diff --git a/static/img/guides/prisma-d1-setup-cover.png b/static/img/guides/prisma-d1-setup-cover.png
new file mode 100644
index 0000000000..a7eecdc16a
Binary files /dev/null and b/static/img/guides/prisma-d1-setup-cover.png differ
diff --git a/static/img/guides/prisma-turborepo-setup.png b/static/img/guides/prisma-turborepo-setup.png
new file mode 100644
index 0000000000..7188060eb1
Binary files /dev/null and b/static/img/guides/prisma-turborepo-setup.png differ
diff --git a/static/img/guides/pulse-trigger-workflow.png b/static/img/guides/pulse-trigger-workflow.png
new file mode 100644
index 0000000000..735fbeecf6
Binary files /dev/null and b/static/img/guides/pulse-trigger-workflow.png differ
diff --git a/static/img/guides/real-time-durable-workflows-cover.svg b/static/img/guides/real-time-durable-workflows-cover.svg
new file mode 100644
index 0000000000..fc898b8d7a
--- /dev/null
+++ b/static/img/guides/real-time-durable-workflows-cover.svg
@@ -0,0 +1,69 @@
+
diff --git a/static/img/guides/schema-migration-cover.png b/static/img/guides/schema-migration-cover.png
new file mode 100644
index 0000000000..932a683334
Binary files /dev/null and b/static/img/guides/schema-migration-cover.png differ
diff --git a/static/img/guides/video-processing-pipeline-cover.svg b/static/img/guides/video-processing-pipeline-cover.svg
new file mode 100644
index 0000000000..6e0ff57629
--- /dev/null
+++ b/static/img/guides/video-processing-pipeline-cover.svg
@@ -0,0 +1,112 @@
+