TypeScript
MongoDB

Prisma introspects a MongoDB schema by sampling the data stored in the given database and inferring the schema of that data.

For the purposes of illustrating introspection, this guide will help you setup a MongoDB from scratch. But if you have a MongoDB database already, feel free to jump to Initializing Prisma in your project.

Setting up your Database

To see this in action, first create a blog database with 2 collections: User and Post. We recommend MongoDB Compass for setting this up:

Create a blog database using Compass

First, add a user to our User collection:

Create a user within the User collection

Next, add some posts to our Post collection. It's important that the ObjectID in userId matches the user you created above.

Create some posts within the Post collection

Initializing Prisma

Now that you have a MongoDB database, the next step is to create a new project and initialize Prisma:

mkdir blog
cd blog
npm init -y
npm install -D prisma
npx prisma init

Initializing Prisma will create a prisma/schema.prisma file. Edit this file to use MongoDB:

prisma/schema.prisma
1datasource db {
2 provider = "mongodb"
3 url = env("DATABASE_URL")
4}
5
6generator client {
7 provider = "prisma-client-js"
8}

Next you'll need to adjust your .env file to point the DATABASE_URL to your MongoDB database

Introspecting MongoDB with Prisma

You're now ready to introspect. Run the following command to introspect your database:

npx prisma db pull

This command introspects our database and writes the inferred schema into your prisma/schema.prisma file:

prisma/schema.prisma
1datasource db {
2 provider = "mongodb"
3 url = env("DATABASE_URL")
4}
5
6generator client {
7 provider = "prisma-client-js"
8}
9
10model Post {
11 id String @id @default(auto()) @map("_id") @db.ObjectId
12 title String
13 userId String @db.ObjectId
14}
15
16model User {
17 id String @id @default(auto()) @map("_id") @db.ObjectId
18 email String
19}

Tweaking the Schema

To be able to join data using Prisma Client, you can add the @relation attributes to our models:

prisma/schema.prisma
1datasource db {
2 provider = "mongodb"
3 url = env("DATABASE_URL")
4}
5
6generator client {
7 provider = "prisma-client-js"
8}
9
10model Post {
11 id String @id @default(auto()) @map("_id") @db.ObjectId
12 title String
13 userId String @db.ObjectId
+ user User @relation(fields: [userId], references: [id])
15}
16
17model User {
18 id String @id @default(auto()) @map("_id") @db.ObjectId
19 email String
+ posts Post[]
21}

We're actively working on MongoDB introspection. Provide feedback for this feature in this issue.

And with that, you're ready to generate Prisma Client.

Edit this page on GitHub