You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Validate guide against prisma-next 0.16.0; fix adoption flow, ObjectId filters, and raw-command mapping
Every command and snippet now runs against a live v6 database on
mongodb-memory-server (mongod 8.0.4 replica set) migrated to
@prisma-next/mongo@0.16.0. Changes that came out of that run:
- Step 4: db init refuses a populated v6 database (validator adds are
classed destructive), and migration plans start from an empty baseline
without a ref, so the adoption path is db update --advance-ref db,
with plan/migrate/verify for every change after that.
- 3c: the typed pipeline builder passes ObjectId values through as
strings, so match on an ObjectId field silently returns nothing;
grouped example no longer filters by authorId and a warning shows the
working rawCommand + ObjectId pattern.
- 3e/quick reference: $runCommandRaw maps to sharing one MongoClient
with the mongo() binding (mongoClient + dbName), shown end to end;
collection-scoped escapes point at db.query.rawCommand.
- Checklist: restore same-database and MongoDB 8.0+ items; rehearsal
commands now match the adoption flow.
- Step 2: note that every discriminator value in existing data needs a
declared variant with at least one field.
- Align snippets with the actual init scaffold (contract.d import,
non-null env assertions), storage-value enum row in common mistakes,
relative docs links, em-dash cleanup.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Copy file name to clipboardExpand all lines: apps/docs/content/docs/guides/next/upgrade-prisma-orm/mongodb.mdx
+78-37Lines changed: 78 additions & 37 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -6,7 +6,7 @@ metaTitle: How to migrate a MongoDB project from Prisma v6 to Prisma Next
6
6
metaDescription: Step-by-step guide to migrating a Prisma ORM v6 MongoDB project to Prisma Next, covering setup, contracts, client calls, migrations, and production cutover.
7
7
---
8
8
9
-
This guide is for developers moving a Prisma ORM v6 MongoDB project to **Prisma Next**. Prisma 7 has **no MongoDB connector**, so Prisma Next is the successor path. This is a **code and workflow migration against the same database** — your data never moves.
9
+
This guide is for developers moving a Prisma ORM v6 MongoDB project to **Prisma Next**. Prisma 7 has **no MongoDB connector**, so Prisma Next is the successor path. This is a **code and workflow migration against the same database**: your data never moves.
10
10
11
11
:::tip[Working with an AI coding agent?]
12
12
@@ -24,7 +24,7 @@ Install the companion [prisma-mongodb-upgrade](https://github.com/prisma/skills/
24
24
25
25
:::info
26
26
27
-
Prisma Next MongoDB is Early Access (GA planned after Postgres), so details can shift between releases — check anything below against the `@prisma-next/*` version you install.
27
+
Prisma Next MongoDB is Early Access (GA planned after Postgres) and evolves quickly, so check anything below against the `@prisma-next/*` version you install. Every command and code example in this guide was validated against `@prisma-next/mongo@0.16.0`.
| Index |`@@index(...)`, synced by `db push`|`@@index(...)` / `@@unique(...)`, applied by migrations |
125
-
| Polymorphism | not supported |`@@discriminator(field)` on the base + `@@base(Base, "value")` on each variant. <br />See the [Base Model and Variants](https://www.prisma.io/docs/orm/next/contract-authoring/psl-syntax#base-models-and-variants)|
126
+
| Polymorphism | not supported |`@@discriminator(field)` on the base + `@@base(Base, "value")` on each variant. <br />See [Base models and variants](/orm/next/contract-authoring/psl-syntax#base-models-and-variants)|
126
127
127
128
A fuller contract putting together enum, embedded type, relation, and polymorphism:
128
129
@@ -168,6 +169,8 @@ model Article {
168
169
}
169
170
```
170
171
172
+
When you use `@@discriminator`, declare a variant for every value the field takes in your existing data: the generated validator only accepts declared values, so writes to documents with an undeclared value fail once the validators are live. A variant model must declare at least one field (an optional one is enough).
173
+
171
174
## 3. Port client calls
172
175
173
176
Names look similar but parity does not hold. This section breaks down each category of operation.
v6's `groupBy` / `aggregate` become a chain of steps. `acc` provides the group totals (`acc.count()`, `acc.max(...)`, etc.) — the equivalent of v6's `_count` / `_sum` / `_max`.
253
+
v6's `groupBy` / `aggregate` become a typed pipeline: build a plan with `db.query`, then run it with `db.execute`. `acc` provides the group totals (`acc.count()`, `acc.max(...)`, and friends), the equivalent of v6's `_count` / `_sum` / `_max`.
Don't add `.match((f) => f.authorId.eq(authorId))` to filter by an `ObjectId` field (`_id`, or a foreign key like `authorId`): the typed builder sends the id through as a plain string, so the stage silently matches nothing. Filter ObjectId fields with the ORM client instead (`db.orm.posts.where({ authorId })` encodes them for you), or run the aggregation as a raw command carrying a real `ObjectId`:
Prisma Next has no `transaction` method for MongoDB yet. For multi-document transactions, use the `mongodb` driver's [Transaction API](https://www.mongodb.com/docs/drivers/node/current/crud/transactions/transaction-conv/).
`db.raw` is collection-scoped, so it has no equivalent for v6's database-level `$runCommandRaw`. For arbitrary commands, construct your own `MongoClient`, pass it to the binding, and use that client directly — the same `db` object keeps giving you the typed ORM.
356
+
`db.raw` is collection-scoped, so v6's database-level `$runCommandRaw` has no ORM equivalent. Construct your own `MongoClient` and pass it to the binding from step 1 in place of `url`: the same client then powers the typed ORM and runs arbitrary commands, sharing one connection pool.
@@ -348,6 +376,8 @@ import { prisma } from './db';
348
376
awaitprisma.$runCommandRaw({ ping: 1 });
349
377
```
350
378
379
+
For raw reads and writes scoped to a single collection (anything the typed builder can't express), you don't need the driver: `db.query.rawCommand(...)` packages a raw command into a plan, as shown in [3c](#3c-aggregations). See [Raw queries](/orm/next/reference/raw-queries) for the full surface.
|`findRaw` / `aggregateRaw`|`db.raw.collection(...).aggregate(...).build()` → `db.execute(plan)`, or `db.query.rawCommand(...)`|
391
+
|`$runCommandRaw`|share a `MongoClient` with the binding, then `mongoClient.db(...).command(...)` (see 3e)|
392
+
|`$transaction(...)`|no wrapper yet; driver sessions on a replica set (see 3d)|
363
393
|`$connect` / `$disconnect`| lazy connect on first use; `db.close()` to disconnect |
364
394
365
395
## 4. Adopt the migration lifecycle
366
396
367
-
v6 MongoDB had no Prisma Migrate — only `db push` (ephemeral, no history). Prisma Next gives MongoDB first-class, contract-driven migrations: reviewable diffs you commit, reproducible across environments, and an auditable schema history.
397
+
v6 MongoDB had no Prisma Migrate, only `db push` (ephemeral, no history). Prisma Next gives MongoDB first-class, contract-driven migrations: reviewable diffs you commit, reproducible across environments, and an auditable schema history.
398
+
399
+
### Bring the v6 database under management
368
400
369
-
Use `db update` for local dev (the `db push` analogue) and the migration workflow for shared/prod. The CLI reads the target from `prisma-next.config.ts`:
401
+
Your database already has collections and data, so bootstrap it with `db update`: it diffs the live database against your contract, applies the delta (the strict validators, plus any indexes the contract declares that v6 never created), and signs the database so Prisma Next recognizes it from then on. The `--advance-ref db` flag records the resulting contract state as the [`db` ref](/orm/next/migrations/the-migration-graph#name-important-states-with-refs), the starting point later migration plans diff from.
370
402
371
403
```bash
372
-
# Local dev: diff the contract against the live DB and apply directly, no history kept.
373
404
npx prisma-next contract emit
374
-
npx prisma-next db update --db "$DATABASE_URL"
405
+
npx prisma-next db update --db "$DATABASE_URL" --dry-run # preview the delta first
406
+
npx prisma-next db update --db "$DATABASE_URL" --advance-ref db
407
+
```
408
+
409
+
Don't reach for `db init` here. It bootstraps only additively, and on a populated database it refuses the validator changes this migration needs, because adding a validator to a collection with existing documents is classed destructive. `db update` applies them after a confirmation prompt.
410
+
411
+
### Every schema change after that
375
412
376
-
# Shared branches / production: write a reviewable migration package, then apply it.
377
-
npx prisma-next migration plan --name add_posts_indexes
378
-
npx prisma-next migrate --db "$DATABASE_URL"
413
+
Use `db update` for local experiments (the `db push` analogue, no history kept) and the migration workflow for shared branches and production:
414
+
415
+
```bash
416
+
npx prisma-next migration plan --name add_posts_indexes # plans from the db ref
417
+
npx prisma-next migrate --db "$DATABASE_URL" --advance-ref db
379
418
npx prisma-next db verify --db "$DATABASE_URL"# check the DB matches the contract
380
419
```
381
420
382
421
**Good to know:**
383
422
384
-
- You never hand-write migration steps — declare indexes and validators in the contract (step 2) and `migration plan` derives the changes.
385
-
-Run `db init` once on a database Prisma Next hasn't managed before, and`db sign`after any manual fix. Interrupted `migrate` runs are resumable — just rerun.
386
-
- Prisma Next adds strict `$jsonSchema` validators by default; make sure existing documents pass them before running in production.
423
+
- You never hand-write migration steps: declare indexes and validators in the contract (step 2) and `migration plan` derives the changes.
424
+
-Interrupted `migrate` runs are resumable; just rerun. After fixing anything by hand, run`db sign`so the signature matches the database again.
425
+
- Prisma Next adds strict `$jsonSchema` validators by default. Make sure existing documents pass them before running in production: once the validators are live, writes to documents that don't match the contract fail with `Document failed validation`.
387
426
388
427
## 5. Pre-flight checklist (before production cutover)
389
428
390
429
Work through this list before you switch production traffic over:
391
430
392
-
-[ ]**Dry run first.** Rehearse the whole flow on a throwaway copy of your database (`contract emit`, `migration plan`, `migrate`, `db verify`) and make sure `db verify` passes before you touch production.
431
+
-[ ]**Same database.** Your Prisma Next config points at the **same** database and connection string as v6.
432
+
-[ ]**Server version.** Your MongoDB server is on 8.0 or newer.
433
+
-[ ]**Dry run first.** Rehearse the whole flow on a throwaway copy of your database (`contract emit`, `db update --dry-run`, `db update`, `db verify`) and make sure `db verify` passes before you touch production.
393
434
-[ ]**Index parity.** The indexes on each collection (`db.collection.getIndexes()`) match your contract.
394
435
-[ ]**Validators.** Your existing documents pass the strict validators Prisma Next adds to each collection (see *Good to know* in step 4).
395
436
-[ ]**Addressing.** Every call site uses storage names like `db.orm.users`, not model names.
@@ -408,4 +449,4 @@ Once you've cut over, this is the day-to-day workflow:
408
449
-**Troubleshooting.**`db verify` checks the database against your contract, and `db sign` records any fixes you make by hand.
409
450
-**Performance.** Your aggregations now compile to native MongoDB pipelines, so it's worth benchmarking them against your old v6 raw calls.
410
451
411
-
See [Prisma Next docs](https://github.com/prisma/prisma-next) for pipeline builder patterns, relation loading strategies, and advanced contract features. This guide gets you across the bridge; Prisma Next's docs are the source of truth from here on.
452
+
See the [Prisma Next docs](/orm/next) for [pipeline builder patterns](/orm/next/reference/pipeline-builder), [relation loading strategies](/orm/next/reference/orm-client), and [advanced contract features](/orm/next/contract-authoring/psl-syntax). This guide gets you across the bridge; Prisma Next's docs are the source of truth from here on.
0 commit comments