Guide
How to Migrate from Mongoose to Prisma 2026




Step-by-step guide to migrating your Mongoose MongoDB models to Prisma with PostgreSQL or MongoDB. Schema conversion, query translation, and handling the.
Contents
Contents
TL;DR
Choose the database and Prisma major before translating queries. If you keep MongoDB, use the pinned Prisma ORM v6.19 example to evaluate schema and query differences on a local copy. For a production move to PostgreSQL, plan a separate data transfer and use the setup for a supported Prisma major. Keep Mongoose when your app needs MongoDB and cannot take on Prisma's compatibility or support trade-offs.
Key Takeaways
- MongoDB keeps your collections and ObjectIds. Review the introspected schema, map existing names, and model embedded documents as composite types.
- PostgreSQL needs a destination schema and a data transfer. Map IDs and load parent records before rows that reference them.
- Both paths generate a typed Prisma Client. Check Mongoose's casting, defaults, validators, and hooks against the generated client's behavior before cutting over.
Why Migrate from Mongoose to Prisma?
Prisma generates a client from schema.prisma. Your query arguments and selected result fields get generated types. Mongoose also ships TypeScript definitions, so compare the generated client with the types and document behavior you already rely on.
Prisma Migrate creates versioned SQL migrations for supported relational databases. For MongoDB, db push can synchronize supported schema changes such as indexes. Use separate data-change scripts for backfills and changes to existing documents.
Start by listing where your app uses Mongoose-specific behavior. Check custom validators, aggregation pipelines, middleware, and places that distinguish a missing field from an explicit null. Use those cases to decide whether switching clients pays off.
Option A: Mongoose MongoDB → Prisma MongoDB
Prisma ORM v7 has no MongoDB connector. Prisma ORM v8 is a release candidate with early-access MongoDB support and a different setup. The walkthrough uses Prisma ORM v6.19.3, which supports MongoDB but is outside its support window. Check the Prisma release status before choosing a production version. Stay on Mongoose if you need a maintained MongoDB stack and cannot accept an early-access connector.
Use a disposable local replica set with representative documents. Prisma uses transactions for nested writes, which require a replica set. Install matching CLI and client versions:
npm install -D prisma@6.19.3
npm install @prisma/client@6.19.3
npx prisma init --datasource-provider mongodb
Set DATABASE_URL to the local copy, then pull its schema:
npx prisma db pull
Introspection samples documents, so review inferred types and optional fields. Add relations to other collections by hand and map any model names that differ from the stored collection names.
The following schema assumes Mongoose's default users and posts collection names. It preserves the embedded profile and assumes posts store the user's ObjectId in authorId. Confirm which side stores the reference in your data.
datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
name String
email String @unique
role Role @default(user)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
profile Profile?
posts Post[]
@@map("users")
}
type Profile {
bio String?
avatar String?
website String?
}
enum Role {
user
admin
}
model Post {
id String @id @default(auto()) @map("_id") @db.ObjectId
title String
content String
published Boolean @default(false)
authorId String @db.ObjectId
author User @relation(fields: [authorId], references: [id])
createdAt DateTime @default(now())
@@map("posts")
}
@map("_id") keeps the stored field name, and @db.ObjectId preserves its BSON type. Set matching annotations on stored ObjectId references and use @@map for the original collection names. Run npx prisma validate and npx prisma generate before translating queries.
Use a composite type for an embedded document and a relation for a stored reference. Compare query results for populated, missing, and explicitly null fields in your local copy. For MongoDB filters that must include missing fields, check Prisma's isSet filter alongside the null case.
Option B: Mongoose MongoDB → Prisma PostgreSQL
Choose PostgreSQL if you need relational constraints and versioned SQL schema changes. Plan how to transform and load the existing documents, then validate that the new tables represent the same records and references.
Map independently queried or repeated embedded records to tables. For this example, each post becomes a row with an authorId foreign key, and the profile's scalar fields become columns on the user row. If your source stores post IDs on the user, derive each post's author reference during the import.
Here is the schema translation. The PostgreSQL example uses the same Prisma ORM v6.19.3 toolchain as the MongoDB fixture for reproducibility. For a production PostgreSQL migration, use the PostgreSQL setup for a supported major.
// BEFORE — Mongoose model definition
import mongoose, { Schema, Document } from 'mongoose';
interface IUser extends Document {
name: string;
email: string;
role: 'user' | 'admin';
profile: {
bio?: string;
avatar?: string;
website?: string;
};
posts: mongoose.Types.ObjectId[];
createdAt: Date;
updatedAt: Date;
}
const UserSchema = new Schema<IUser>(
{
name: { type: String, required: true, trim: true },
email: { type: String, required: true, unique: true, lowercase: true },
role: { type: String, enum: ['user', 'admin'], default: 'user' },
profile: {
bio: String,
avatar: String,
website: String,
},
posts: [{ type: Schema.Types.ObjectId, ref: 'Post' }],
},
{ timestamps: true }
);
export const User = mongoose.model<IUser>('User', UserSchema);
// AFTER — Prisma schema (PostgreSQL)
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id String @id @default(cuid())
name String
email String @unique
role Role @default(user)
bio String? // Flat — embedded doc fields become columns
avatar String?
website String?
posts Post[] // Relation — replaces ObjectId array
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
enum Role {
user
admin
}
model Post {
id String @id @default(cuid())
title String
content String
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
For this example, point DATABASE_URL to a disposable local PostgreSQL database and run npx prisma migrate dev --name init. Review the SQL in prisma/migrations/ and commit it with the schema. The migration creates the destination tables. Write and rehearse a separate import that loads users and then posts using the mapped IDs.
Handling ObjectId → UUID
The MongoDB example stores ObjectIds. If you replace them with generated PostgreSQL IDs, translate every reference that points to an old ID.
For existing data, keep the original ObjectId string in a unique legacyId column while you assign new IDs. Load the parent rows first, resolve their old IDs to the new keys, and use those keys to load dependent records.
model User {
id String @id @default(uuid())
legacyId String? @unique // Temporary — stores original MongoDB ObjectId
name String
email String @unique
}
Keep the mapping through verification and the rollback window. If the new database accepts writes after cutover, plan how to replay or reconcile those writes before routing traffic back.
Query Translation Table
Migrating query code is the most mechanical part of the migration. Here is a side-by-side reference for the most common patterns:
| Operation | Mongoose | Prisma |
|---|---|---|
| Find by ID | User.findById(id) | prisma.user.findUnique({ where: { id } }) |
| Find by unique email | User.findOne({ email }) | prisma.user.findUnique({ where: { email } }) |
| Find many with filter | User.find({ role: 'admin' }) | prisma.user.findMany({ where: { role: 'admin' } }) |
| Sort ascending and limit results | .sort('name').limit(pageSize) | { orderBy: { name: 'asc' }, take: pageSize } |
| Create | User.create({ name, email }) | prisma.user.create({ data: { name, email } }) |
| Update by ID | User.findByIdAndUpdate(id, { $set: data }, { new: true }) | prisma.user.update({ where: { id }, data }) |
| Update many | User.updateMany(filter, { $set: data }) | prisma.user.updateMany({ where: filter, data }) |
| Delete by ID | User.findByIdAndDelete(id) | prisma.user.delete({ where: { id } }) |
| Count | User.countDocuments({ role: 'admin' }) | prisma.user.count({ where: { role: 'admin' } }) |
| Populate relation | .populate('posts') | { include: { posts: true } } |
Use include to read related records and select to limit the returned fields. Check query logs before assuming a performance gain. Test missing records too, since Prisma's update and delete throw when the target record is absent.
// CRUD Operations side by side:
// ─── CREATE ───────────────────────────────────────────────────────────
// Mongoose:
const user = await User.create({
name: 'Alice',
email: 'alice@example.com',
role: 'admin',
});
// Prisma:
const user = await prisma.user.create({
data: {
name: 'Alice',
email: 'alice@example.com',
role: 'admin',
},
});
// ─── READ ─────────────────────────────────────────────────────────────
// Mongoose:
const user = await User.findById(id);
const userByEmail = await User.findOne({ email: 'alice@example.com' });
const admins = await User.find({ role: 'admin' }).sort({ name: 1 }).limit(10);
// Prisma:
const user = await prisma.user.findUnique({ where: { id } });
const userByEmail = await prisma.user.findUnique({ where: { email: 'alice@example.com' } });
const admins = await prisma.user.findMany({
where: { role: 'admin' },
orderBy: { name: 'asc' },
take: 10,
});
// ─── UPDATE ───────────────────────────────────────────────────────────
// Mongoose:
await User.findByIdAndUpdate(id, { $set: { name: 'Bob' } }, { new: true });
await User.updateMany({ role: 'admin' }, { $set: { role: 'user' } });
// Prisma:
await prisma.user.update({ where: { id }, data: { name: 'Bob' } });
await prisma.user.updateMany({ where: { role: 'admin' }, data: { role: 'user' } });
// ─── DELETE ───────────────────────────────────────────────────────────
// Mongoose:
await User.findByIdAndDelete(id);
await User.deleteMany({ role: 'admin' });
// Prisma:
await prisma.user.delete({ where: { id } });
await prisma.user.deleteMany({ where: { role: 'admin' } });
Relations and Populate → Include
In the Prisma models above, Post.authorId drives the relation. If Mongoose used the user's stored array of post IDs, confirm the Prisma query returns the same posts and ordering before changing the caller.
// Mongoose — populate the stored references:
const user = await User.findById(id).populate('posts');
// Prisma — include posts through the defined relation:
const user = await prisma.user.findUnique({
where: { id },
include: {
posts: true,
},
});
// Nested includes with filters:
const user = await prisma.user.findUnique({
where: { id },
include: {
posts: {
where: { published: true },
orderBy: { createdAt: 'desc' },
take: 10,
},
},
});
// Select specific fields to reduce payload:
const user = await prisma.user.findUnique({
where: { id },
select: {
id: true,
name: true,
email: true,
posts: {
select: { id: true, title: true },
},
},
});
Mongoose Middleware → Prisma Extensions
Prisma query extensions can wrap specific client operations. This illustrative create hook assumes a separate model with a password field and a configured hash function. Port and test every write path that relied on the Mongoose hook, including updates or bulk operations. Prefer a shared application function when several operations need the same behavior.
// Mongoose pre-save hook:
UserSchema.pre('save', async function () {
if (this.isModified('password')) {
this.password = await bcrypt.hash(this.password, hashRounds);
}
});
// Prisma extensions (current API):
const prismaWithHooks = prisma.$extends({
query: {
user: {
async create({ args, query }) {
if (args.data.password) {
args.data.password = await bcrypt.hash(args.data.password, hashRounds);
}
return query(args);
},
},
},
});
Package Health
| Client or tool | TypeScript | Schema and data workflow |
|---|---|---|
prisma | Generates the schema-specific client | Prisma Migrate for relational databases. Use db pull for MongoDB introspection and review db push changes on a local copy |
@prisma/client | Generated query and result types | Install the same version as the CLI. MongoDB support depends on the Prisma major |
mongoose | Bundles TypeScript definitions and supports schema type inference | Model validation and middleware for MongoDB. Handle data changes with scripts or separate migration tooling |
Migration Checklist
- Inventory the models. List embedded data, references, validators, casting rules, and middleware. Include existing documents that omit fields.
- Choose your database and Prisma major. Check connector support before installing the CLI and client. Use the pinned versions above for the examples.
- Translate and validate the schema locally. For MongoDB, pull the schema from a copy, keep collection names and ObjectIds, and add missing relations. Review index changes before using
db pushon the copy. For PostgreSQL, create the destination schema and review the generated SQL. - Transfer data for the PostgreSQL path. Map IDs, import parents before dependents, and check counts, uniqueness constraints, and missing references.
- Port queries and write behavior. Recheck result shape, null and missing values, validation, normalization, timestamps, and hooks. Give each collection a clear owner during an incremental migration.
- Rehearse cutover and rollback. Compare outputs with representative data, track writes during the switch, and decide how to reconcile them if you revert.
When to Choose Prisma vs Stay on Mongoose
Choose Prisma when generated query types and the destination database's schema workflow justify the port. If you keep MongoDB, prototype queries against a local copy and check that the connector covers the features and support window you need.
Stay on Mongoose if your app depends on document hooks or MongoDB operations you cannot reproduce through the Prisma connector you plan to ship. Test those operations before committing to a migration.
For a gradual migration, give each client its own connection pool and move a collection's write ownership together with its validation and defaults. During read-only comparisons, run the same lookups in each client and verify that missing fields and related records behave as expected.
Explore related guides: compare the two ORMs directly on PkgPulse's Mongoose vs Prisma comparison, read the full Mongoose vs Prisma 2026 breakdown, or see what developers are building with the Prisma package page.