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 previewFeatures = ["mongoDb"]
9}

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
1generator client {
2 provider = "prisma-client-js"
3 previewFeatures = ["mongoDb"]
4}
5
6datasource db {
7 provider = "mongodb"
8 url = env("DATABASE_URL")
9}
10
11model Post {
12 id String @id @default(dbgenerated()) @map("_id") @db.ObjectId
13 title String
14 userId String @db.ObjectId
15}
16
17model User {
18 id String @id @default(dbgenerated()) @map("_id") @db.ObjectId
19 email String
20}

Tweaking the Schema

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

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

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

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

Edit this page on GitHub