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.
- Node.js installed in your system with the supported version
- A MongoDB database accessible via connection string
mkdir hello-prisma
cd hello-prismaInitialize a TypeScript project:
bun init
bun add typescript tsx @types/node --dev
bunx tsc --initpnpm init
pnpm add typescript tsx @types/node --save-dev
pnpm tsc --inityarn init
yarn add typescript tsx @types/node --dev
yarn tsc --initnpm init
npm install typescript tsx @types/node --save-dev
npx tsc --initInstall the packages needed for this quickstart:
bun add prisma@6.19.3 @types/node --devpnpm add prisma@6.19.3 @types/node --save-devyarn add prisma@6.19.3 @types/node --devnpm install prisma@6.19.3 @types/node --save-devbun add @prisma/client@6.19.3 dotenvpnpm add @prisma/client@6.19.3 dotenvyarn add @prisma/client@6.19.3 dotenvnpm 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@6and@prisma/client@6to automatically get the latest v6 release.
Here's what each package does:
prisma- The Prisma CLI for running commands likeprisma init,prisma db push, andprisma generate@prisma/client- The Prisma Client library for querying your databasedotenv- Loads environment variables from your.envfile
[!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 likeprisma init,prisma db push, andprisma generate@prisma/client- The Prisma Client library for querying your databasedotenv- Loads environment variables from your.envfile
Update tsconfig.json for ESM compatibility:
{
"compilerOptions": {
"module": "ESNext",
"moduleResolution": "bundler",
"target": "ES2023",
"strict": true,
"esModuleInterop": true,
"ignoreDeprecations": "6.0"
}
}Update package.json to enable ESM:
{
"type": "module"
}You can now run Prisma CLI commands using your package manager:
bunx prismapnpm prismayarn prismanpx prismaNext, 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:
bunx --bun prisma init --datasource-provider mongodb --output ../generated/prismapnpm prisma init --datasource-provider mongodb --output ../generated/prismayarn prisma init --datasource-provider mongodb --output ../generated/prismanpx prisma init --datasource-provider mongodb --output ../generated/prismaThis command does a few things:
- Creates a
prisma/directory with aschema.prismafile for your database connection and schema models - Creates a
.envfile in the root directory for environment variables - Creates a
prisma.config.tsfile for Prisma configuration
The generated prisma.config.ts file looks like this:
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:
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:
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:
DATABASE_URL="mongodb+srv://username:password@cluster.mongodb.net/mydb"Open prisma/schema.prisma and add the following models:
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:
bunx prisma db pushpnpm prisma db pushyarn prisma db pushnpx prisma db pushThis 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:
import "dotenv/config";
import { PrismaClient } from "../generated/prisma/client";
const prisma = new PrismaClient();
export { prisma };Create a script.ts file to test your setup:
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:
bunx tsx script.tspnpm dlx tsx script.tsyarn dlx tsx script.tsnpx tsx script.tsYou 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 failederror, add?authSource=adminto the end of your connection string. - Empty database name: If you see an
Error code 8000 (AtlasError): empty database name not allowederror, append the database name to your connection URL. See this GitHub issue for details.