DEV Community

Cover image for Prisma + MongoDB “Hello World”
Franck Pachot
Franck Pachot

Posted on

Prisma + MongoDB “Hello World”

Prisma is an ORM (Object-Relational Mapper). With MongoDB, it acts as an Object Document Mapper, mapping collections to TypeScript models and providing a consistent, type-safe query API.

MongoDB is a document database with a flexible schema. Prisma does not provide schema migrations for MongoDB, but it supports nested documents and embedded types to take advantage of MongoDB’s data locality.

This article walks through a minimal “Hello World” setup on a Docker environment:

  • Run MongoDB as a replica set
  • Connect to it using Prisma
  • Insert a "Hello World" document
  • Read and display all documents

Start MongoDB as a replica set

Prisma requires MongoDB to run as a replica set. While MongoDB supports many operations without transactions, Prisma relies on MongoDB sessions and transactional behavior internally, which are only available on replica sets.

Start MongoDB in a Docker container with replica set support enabled:

docker run --name mg -d mongo --replSet rs0

Enter fullscreen mode Exit fullscreen mode

Initialize the replica set (a single‑node replica set is sufficient for local development and testing):

docker exec -it mg mongosh --eval "rs.initiate()"

Enter fullscreen mode Exit fullscreen mode

Start a Node.js container

Start a Node.js container that can access MongoDB using the hostname mongo:

docker run --rm -it --link mg:mongo node bash

Enter fullscreen mode Exit fullscreen mode

Prepare the Node.js environment

Update the package manager, install an editor, update npm, disable funding messages, and move to the working directory:

apt-get update
apt-get install -y vim
npm install -g npm@11.9.0
npm config set fund false
cd /home
Enter fullscreen mode Exit fullscreen mode

Install Prisma Client and enable ES modules

Install Prisma Client and enable ES modules by adding "type": "module" to package.json:

npm install @prisma/client@6.19.0
sed -i '1s/{/{\n  "type": "module",/' package.json

Enter fullscreen mode Exit fullscreen mode

Using ES modules enables standard import syntax and aligns the project with modern Node.js tooling.

Install Prisma CLI and TypeScript tooling

Install the Prisma CLI and supporting tooling, and generate the initial Prisma configuration:

npm install -D prisma@6.19.0 @types/node 
npm install -D tsx
npx prisma init

Enter fullscreen mode Exit fullscreen mode

Configure the Prisma schema

Edit prisma/schema.prisma, change the provider from postgresql to mongodb, and define a minimal Message model:

generator client {
  provider = "prisma-client"
  output   = "../generated/prisma"
}

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

model Message {
  id        String   @id @default(auto()) @map("_id") @db.ObjectId
  content   String
  createdAt DateTime @default(now())
}

Enter fullscreen mode Exit fullscreen mode

Prisma maps MongoDB’s _id field to a String backed by an ObjectId.
The prisma-client generator produces TypeScript output in a custom directory to avoid using @prisma/client.

Configure the database connection

Define the MongoDB connection string in .env:

DATABASE_URL="mongodb://mongo:27017/test"

Enter fullscreen mode Exit fullscreen mode

Prisma reads DATABASE_URL at generation time, while the application reads it at runtime. Importing dotenv/config ensures both environments are consistent.

Generate the Prisma client

Generate the Prisma client from the schema:

npx prisma generate

Enter fullscreen mode Exit fullscreen mode

This produces TypeScript client files in generated/prisma.

Write the “Hello World” program

Create prisma/index.ts:

import 'dotenv/config'
import { PrismaClient } from '../generated/prisma/client.ts'

const prisma = new PrismaClient()

async function main() {
  await prisma.$connect()
  console.log('Connected to MongoDB')

  await prisma.message.create({
    data: {
      content: 'Hello World',
    },
  })

  const messages = await prisma.message.findMany()

  console.log('Messages in database:')
  for (const message of messages) {
    console.log(`- ${message.content} at ${message.createdAt}`)
  }
}

main()
  .catch(console.error)
  .finally(() => prisma.$disconnect())
Enter fullscreen mode Exit fullscreen mode

This program connects to MongoDB, inserts a “Hello World” document, and prints all stored messages.

Run the program

For running TypeScript directly in modern Node.js projects, tsx is generally preferred over ts-node due to better ESM support and faster startup.

Execute the TypeScript file:

npx tsx prisma/index.ts

Enter fullscreen mode Exit fullscreen mode

Output:

Connected to MongoDB
Messages in database:
- Hello World at Wed Feb 11 2026 17:36:08 GMT+0000 (Coordinated Universal Time)
Enter fullscreen mode Exit fullscreen mode

Conclusion and final note on schemas in MongoDB

This example shows a minimal Prisma + MongoDB setup:

  • MongoDB running as a replica set
  • Prisma configured for MongoDB
  • A single model with one insert and one read

From here, you can add schema evolution, indexes, and more complex queries while keeping the same core configuration.

MongoDB is often called schemaless, but that’s misleading in practice, as we started to declare the database schema in schema.prisma and generate the client for it. Real‑world MongoDB applications are schema‑driven, with structure defined in the application layer through models, validation rules, and access patterns.

Unlike relational databases—where the schema is enforced in the database and then mapped into the application—MongoDB keeps a consistent document structure across all layers: in‑memory cache, on‑disk storage, and application models. This preserves data locality, eliminates ORM overhead and migration scripts, and increases development velocity. It aligns well with Domain-Driven Design, where each bounded context has its own database, which does not need to be fully normalized or shared across all enterprise application.

Prisma makes this explicit by defining the schema in code, providing type safety and consistency while keeping MongoDB’s document model flexible as your application evolves.

Top comments (0)