Prisma + MongoDB “Hello World”
Source: Dev.to
Prisma + MongoDB “Hello World” on Docker
Prisma is an ORM (Object‑Relational Mapper). With MongoDB it works 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 in a Docker environment:
- Run MongoDB as a replica set
- Connect to it using Prisma
- Insert a “Hello World” document
- Read and display all documents
1. Start MongoDB as a replica set
Prisma requires MongoDB to run as a replica set because it relies on sessions and transactional behavior internally.
# Start a single‑node replica set
docker run --name mg -d mongo --replSet rs0
Initialize the replica set (a single‑node replica set is sufficient for local development):
docker exec -it mg mongosh --eval "rs.initiate()"
2. Start a Node.js container
Create a container that can reach the MongoDB instance via the hostname mongo:
docker run --rm -it --link mg:mongo node bash
3. Prepare the Node.js environment
apt-get update
apt-get install -y vim
npm install -g npm@11.9.0
npm config set fund false
cd /home
4. Install Prisma Client and enable ES modules
npm install @prisma/client@6.19.0
# Add "type": "module" to package.json
sed -i '1s/{/{\n "type": "module",/' package.json
Using ES modules enables the standard import syntax and aligns the project with modern Node.js tooling.
5. Install Prisma CLI and TypeScript tooling
npm install -D prisma@6.19.0 @types/node
npm install -D tsx
npx prisma init
6. Configure the Prisma schema
Edit prisma/schema.prisma:
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())
}
Prisma maps MongoDB’s _id field to a String backed by an ObjectId. The prisma-client generator outputs TypeScript files to a custom directory to avoid using the default @prisma/client package.
7. Configure the database connection
Create a .env file with the MongoDB connection string:
DATABASE_URL="mongodb://mongo:27017/test"
Prisma reads DATABASE_URL at generation time, while the application reads it at runtime. Importing dotenv/config ensures both environments stay in sync.
8. Generate the Prisma client
npx prisma generate
The command produces TypeScript client files in generated/prisma.
9. 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');
// Insert a document
await prisma.message.create({
data: {
content: 'Hello World',
},
});
// Read all documents
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());
The program connects to MongoDB, inserts a “Hello World” document, and prints all stored messages.
10. Run the program
For running TypeScript directly in modern Node.js projects, tsx is preferred over ts-node because of better ESM support and faster startup.
npx tsx prisma/index.ts
Expected output
Connected to MongoDB
Messages in database:
- Hello World at Wed Feb 11 2026 17:36:08 GMT+0000 (Coordinated Universal Time)
Conclusion & Note on Schemas in MongoDB
This example demonstrates 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. In this workflow we declare the database schema in schema.prisma and generate a type‑safe client from 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 inside the database and then mapped into the application—MongoDB keeps the schema enforcement in the application code, which Prisma helps to make type‑safe and ergonomic.
The document structure spans 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 the entire 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.