Skip to main content
Prisma Documentation Docs

Search documentation

Type to search this documentation.

On this pageOverview

MongoDB

MongoDB is a popular NoSQL document database. In this guide, you will learn how to set up a new TypeScript project from scratch, connect it to MongoDB using Prisma ORM, and generate a Prisma Client for type-safe access to your database.

mkdir hello-prisma

cd hello-prisma

Initialize a TypeScript project:

title="bun"
bun init

bun add typescript tsx @types/node --dev

bunx tsc --init
pnpm
pnpm init
pnpm add typescript tsx @types/node --save-dev
pnpm tsc --init
yarn
yarn init
yarn add typescript tsx @types/node --dev
yarn tsc --init
npm
npm init
npm install typescript tsx @types/node --save-dev
npx tsc --init

Install the packages needed for this quickstart:

title="bun"
bun add prisma@6.19.3 @types/node --dev
pnpm
pnpm add prisma@6.19.3 @types/node --save-dev
yarn
yarn add prisma@6.19.3 @types/node --dev
npm
npm install prisma@6.19.3 @types/node --save-dev
bun add @prisma/client@6.19.3 dotenv
Bash
pnpm add @prisma/client@6.19.3 dotenv
Bash
yarn add @prisma/client@6.19.3 dotenv
Bash
npm install @prisma/client@6.19.3 dotenv

[!NOTE] Prisma v6.19 and MongoDB

This is the latest stable version of Prisma ORM v6 that fully supports MongoDB. MongoDB support for Prisma ORM v7 is coming soon. You can also install prisma@6 and @prisma/client@6 to automatically get the latest v6 release.

Here's what each package does:

  • prisma - The Prisma CLI for running commands like prisma init, prisma db push, and prisma generate
  • @prisma/client - The Prisma Client library for querying your database
  • dotenv - Loads environment variables from your .env file

[!NOTE] MongoDB doesn't require driver adapters since Prisma ORM connects directly to MongoDB.

Here's what each package does:

  • prisma - The Prisma CLI for running commands like prisma init, prisma db push, and prisma generate
  • @prisma/client - The Prisma Client library for querying your database
  • dotenv - Loads environment variables from your .env file

Update tsconfig.json for ESM compatibility:

title="tsconfig.json"
{

  "compilerOptions": {

    "module": "ESNext",

    "moduleResolution": "bundler",

    "target": "ES2023",

    "strict": true,

    "esModuleInterop": true,

    "ignoreDeprecations": "6.0"

  }

}

Update package.json to enable ESM:

title="package.json"
{

  "type": "module"

}

You can now run Prisma CLI commands using your package manager:

bunx prisma
Bash
pnpm prisma
Bash
yarn prisma
Bash
npx prisma

Next, set up your Prisma ORM project by creating your Prisma Schema file with the following command:

Next, set up your Prisma ORM project by creating your Prisma Schema file with the following command:

title="bun"
bunx --bun prisma init --datasource-provider mongodb --output ../generated/prisma
pnpm
pnpm prisma init --datasource-provider mongodb --output ../generated/prisma
yarn
yarn prisma init --datasource-provider mongodb --output ../generated/prisma
npm
npx prisma init --datasource-provider mongodb --output ../generated/prisma

This command does a few things:

  • Creates a prisma/ directory with a schema.prisma file for your database connection and schema models
  • Creates a .env file in the root directory for environment variables
  • Creates a prisma.config.ts file for Prisma configuration

The generated prisma.config.ts file looks like this:

title="prisma.config.ts"
import { defineConfig, env } from "prisma/config";

export default defineConfig({

  schema: "prisma/schema.prisma",

  migrations: {

    path: "prisma/migrations",

  },

  engine: "classic",

  datasource: {

    url: env("DATABASE_URL"),

  },

});

Add dotenv to prisma.config.ts so that Prisma can load environment variables from your .env file:

title="prisma.config.ts"
import "dotenv/config"; 

import { defineConfig, env } from "prisma/config";

export default defineConfig({

  schema: "prisma/schema.prisma",

  migrations: {

    path: "prisma/migrations",

  },

  engine: "classic",

  datasource: {

    url: env("DATABASE_URL"),

  },

});

The generated schema uses the ESM-first prisma-client generator with a custom output path:

title="prisma/schema.prisma"
generator client {

  provider = "prisma-client"

  output   = "../generated/prisma"

}

datasource db {

  provider = "mongodb"

  url = env("DATABASE_URL")

}

Update your .env file with your MongoDB connection string:

title=".env"
DATABASE_URL="mongodb+srv://username:password@cluster.mongodb.net/mydb"

Open prisma/schema.prisma and add the following models:

title="prisma/schema.prisma"
generator client {

  provider = "prisma-client"

  output   = "../generated/prisma"

}

datasource db {

  provider = "mongodb"

  url = env("DATABASE_URL")

}

model User { 

  id    String  @id @default(auto()) @map("_id") @db.ObjectId

  email String  @unique

  name  String?

  posts Post[]

} 

model Post { 

  id        String  @id @default(auto()) @map("_id") @db.ObjectId

  title     String

  content   String?

  published Boolean @default(false) 

  author    User    @relation(fields: [authorId], references: [id]) 

  authorId  String  @db.ObjectId

} 

MongoDB doesn't support migrations like relational databases. Instead, use db push to sync your schema:

title="bun"
bunx prisma db push
pnpm
pnpm prisma db push
yarn
yarn prisma db push
npm
npx prisma db push

This command:

  • Creates the collections in MongoDB based on your schema
  • Automatically generates Prisma Client

Now that you have all the dependencies installed, you can instantiate Prisma Client:

title="lib/prisma.ts"
import "dotenv/config";

import { PrismaClient } from "../generated/prisma/client";

const prisma = new PrismaClient();

export { prisma };

Create a script.ts file to test your setup:

title="script.ts"
import { prisma } from "./lib/prisma";

async function main() {

  // Create a new user with a post

  const user = await prisma.user.create({

    data: {

      name: "Alice",

      email: "alice@prisma.io",

      posts: {

        create: {

          title: "Hello World",

          content: "This is my first post!",

          published: true,

        },

      },

    },

    include: {

      posts: true,

    },

  });

  console.log("Created user:", user);

  // Fetch all users with their posts

  const allUsers = await prisma.user.findMany({

    include: {

      posts: true,

    },

  });

  console.log("All users:", JSON.stringify(allUsers, null, 2));

}

main()

  .then(async () => {

    await prisma.$disconnect();

  })

  .catch(async (e) => {

    console.error(e);

    await prisma.$disconnect();

    process.exit(1);

  });

Run the script:

title="bun"
bunx tsx script.ts
pnpm
pnpm dlx tsx script.ts
yarn
yarn dlx tsx script.ts
npm
npx tsx script.ts

You should see the created user and all users printed to the console.

You can use MongoDB Atlas, the MongoDB shell, or MongoDB Compass to view and manage your data.

Prisma ORM is set up. These are the pages you are most likely to need next:

  • Learn more about Prisma Client: Explore the Prisma Client API for advanced querying, filtering, and relations
  • Database migrations: Learn about Prisma Migrate for evolving your database schema
  • Performance optimization: Discover query optimization techniques
  • Build a full application: Check out our framework guides to integrate Prisma ORM with Next.js, Express, and more
  • Join the community: Connect with other developers on Discord
  • Authentication failed: If you see a SCRAM failure: Authentication failed error, add ?authSource=admin to the end of your connection string.
  • Empty database name: If you see an Error code 8000 (AtlasError): empty database name not allowed error, append the database name to your connection URL. See this GitHub issue for details.
Suggest an edit

Propose a replacement for this page. The site team reviews it before applying any changes.

Export
Documentation menu