Isaac.

Prisma with MongoDB

Use Prisma ORM with MongoDB for document databases.

By EMEPublished: February 20, 2025
prismamongodbdocument databasenosql

A Simple Analogy

Prisma with MongoDB is like using a type-safe API for documents. Get schema validation with document flexibility.


Why Prisma + MongoDB?

  • Type safety: Document structure in TypeScript
  • Flexibility: MongoDB's document model
  • Migrations: Still managed by Prisma
  • Relationships: Handle embedded and references
  • Consistency: Single query API

Setup

datasource db {
  provider = "mongodb"
  url      = env("DATABASE_URL")
}

generator client {
  provider = "prisma-client-js"
}
mongodb://user:password@localhost:27017/mydb

MongoDB Schema

model User {
  id    String  @id @default(auto()) @map("_id") @db.ObjectId
  email String  @unique
  name  String
  profile Profile?
}

model Profile {
  id     String @id @default(auto()) @map("_id") @db.ObjectId
  bio    String
  user   User   @relation(fields: [userId], references: [id])
  userId String @unique @db.ObjectId
}

Queries

// Create
const user = await prisma.user.create({
  data: {
    email: 'alice@example.com',
    name: 'Alice'
  }
});

// Find
const user = await prisma.user.findUnique({
  where: { id: userId },
  include: { profile: true }
});

// Update
await prisma.user.update({
  where: { id: userId },
  data: { name: 'Updated' }
});

// Array operations
await prisma.user.update({
  where: { id: userId },
  data: {
    tags: {
      push: ['new-tag']
    }
  }
});

Best Practices

  1. Indexes: Create for common queries
  2. Validation: Use Prisma validators
  3. Transactions: Atomic operations
  4. Embedded docs: Use for one-to-one
  5. References: Use for one-to-many

Related Concepts

  • MongoDB aggregation
  • Mongoose
  • Document design
  • Data modeling

Summary

Prisma with MongoDB combines type safety with document flexibility for modern NoSQL applications.