MongoDB.local SF, Jan 15: See the speaker lineup & ship your AI vision faster. Use WEB50 to save 50%
Find out more >
Docs Menu
Docs Home
/ /

Tutorial: Integrate with Prisma

Prisma is an open source Object Relational Mapper (ORM) for Node.js. It supports both JavaScript and TypeScript, but it is primarily used with TypeScript to help you write readable and type-safe code.

Warning

MongoDB Support for Prisma ORM v7

The MongoDB Node.js driver does not yet support Prisma ORM version 7. Use the latest available version 6.x release of Prisma ORM when working with MongoDB.

Schemas help developers avoid data inconsistency issues over time by defining the structure of your collection's documents. While you can define a schema at the database level within MongoDB, Prisma lets you define a schema at the application level. Because the Prisma Client is aware of the schema, developers using the Prisma Client have access to auto-completing queries.

Generally, data that is accessed together should be stored together in a MongoDB collection. Prisma supports using embedded documents to keep data together. In use cases where you must store related data in separate MongoDB collections, you must include one document's _id field in another document. Prisma streamlines this process and assists you in organizing this related data, while also maintaining referential integrity of the data.

When you use references to model relations between collections, you can add the @relation attribute to your Prisma schema to enable Prisma Client to access those relations, emulate referential actions, and help maintain referential integrity.

To learn more about efficient data modeling in MongoDB, see Reduce $lookup Operations in the MongoDB Server manual.

MongoDB has a flexible schema by default. When you introspect an existing MongoDB database by using the prisma db pull command, Prisma samples up to 1000 random documents from each collection to infer the schema structure.

If your collection contains fields with inconsistent data types across documents, Prisma maps those fields to the Json type and outputs a warning. This enables you to read all existing data, but it reduces type safety benefits. To resolve this, you can manually update the data to use consistent types, and then run prisma db pull again to regenerate the schema with proper type definitions. For more information, see Troubleshooting Type Conflicts.

This tutorial shows how to perform the following actions:

  • Download an example Prisma application

  • Configure your Prisma schema

  • Create and populate a MongoDB database with sample data

  • Make the example application compatible with MongoDB

  • Run the application

1

Before you begin this tutorial, ensure you have the following components prepared:

  • A MongoDB Atlas account with a configured cluster. To view instructions, see the MongoDB Get Started guide.

  • Node.js v16.20.1 or later.

2

Clone or download the example application from the Prisma examples repository.

This example is a simple blog content management platform that uses a SQLite database. The following steps modify the application to use MongoDB instead of SQLite.

3

Navigate to the prisma/schema.prisma file in the example application directory. In the datasource db object of this file, set the provider field to "mongodb" and the url field to your Atlas connection URI.

In the User model in the same file, change the id field type from Int to String and set the default value to auto(). The id property must map to the MongoDB _id field. You must also instruct Prisma to set the data type for this property to ObjectId.

In the Post model, perform the same changes to the id field as you did in the User model. You must also change the authorId field type from Int to String and set the data type to ObjectId.

Your schema.prisma file should resemble the following:

generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "mongodb"
url = "<your connection URI>"
}
model Post {
id String @id @default(auto()) @map("_id") @db.ObjectId
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
title String
content String?
published Boolean @default(false)
viewCount Int @default(0)
author User @relation(fields: [authorId], references: [id])
authorId String @db.ObjectId
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
email String @unique
name String?
posts Post[]
}

This schema defines separate User and Post collections in your MongoDB database, where each Post contains a reference to a User.

Once you have made these changes, navigate to the project directory in your terminal and run the following commands to install the necessary dependencies and generate the schema:

npm install
npx prisma generate

Note

If you make any further changes to the schema, you must re-run the npx prisma generate command for the changes to take effect.

4

To populate the database with sample data, run the prisma/seed.ts file in the example project by running the following command:

npx prisma db seed

This creates the User and Post collections as defined by the schema.prisma file and populates them with sample data.

5

Navigate to the src directory of the example project. In the pages/api/post/[id].ts and pages/api/publish/[id].ts files, replace all instances of Number(postId) with postId. This is necessary because the id fields in the schema are now of type String instead of Int.

6

To start the application, run the following command from the project directory:

npm run dev

Navigate to http://localhost:3000 in your web browser to view and run the application. You can use the application to create, draft, publish, and delete blog posts. You can reference the API route definitions in the pages/api folder of the example project.

If your MongoDB collections contain fields that use inconsistent data types across documents, Prisma Client might throw errors when querying data that doesn't match the expected type from your schema.

You can perform the following actions to address this:

  1. Review the warnings and comments in your Prisma schema after running prisma db pull to identify fields that use conflicting types.

  2. Update your data to use consistent types across all documents in the collection.

  3. Run prisma db pull again to regenerate your schema that includes the corrected types.

Alternatively, you can leave the field as type Json if you need to maintain flexibility. However, this reduces the type safety benefits that Prisma provides.

To learn more about Prisma, see the Prisma documentation.

To view and download a full version of the application in this tutorial, see the prisma-mongodb-nextjs-example GitHub repository.

Back

Mongoose Get Started

On this page