Connect MongoDB Using Prisma ORM in NestJS

Let’s connect a mongoDB to NestJS application 👉

Neel Sabne
5 min readAug 2, 2022

🚨 Important Note 🚨

👉 The MongoDB connector for Prisma is still in preview.

👉 Also, before we begin this tutorial, please make sure that your MongoDB deployment is configured with replica sets.

One simple way for this is to use MongoDB Atlas to launch a free instance that has replica set support out of the box.

Here’s a guide to convert standalone deployment to replica sets.

For more information — head over to Prisma’s Docs.

1. Create a new NestJS application

We can begin by using this simple command :

$ npm i -g @nestjs/cli
$ nest new project-name
$ cd project-name

2. Install Prisma CLI

Let’s Install the Prisma CLI tool. We can install this as a development dependency.

$ npm install prisma --save-dev

3. Initialize Prisma in application

Now we can use the CLI tool to create a couple of Prisma-related files. Run this command to begin.

$ npx prisma init

This command does two things:

  • Creates a new directory called prisma that contains a file called schema.prisma, which contains the Prisma schema with your database connection variable and schema models
  • Creates the .env file in the root directory of the project, which is used for defining environment variables (such as your database connection)

4. Connect your database

To connect your database, you need to set the url field of the datasource block in your Prisma schema to your database connection URL:

file path : prisma/schema.prisma

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

In this case, the url is set via an environment variable which is defined in .env (the example uses a MongoDB Atlas URL):

file path : /.env

DATABASE_URL="mongodb+srv://test:test@cluster0.ns1yp.mongodb.net/myFirstDatabase"

You now need to adjust the connection URL to point to your own database.

The format of the connection URL for your database depends on the database you use. For MongoDB, it looks as follows (the parts spelled all-uppercased are placeholders for your specific connection details):

mongodb://USERNAME:PASSWORD@HOST:PORT/DATABASE

Here’s a short explanation of each component:

  • USERNAME: The name of your database user
  • PASSWORD: The password for your database user
  • HOST: The host where a mongod (or mongos) instance is running
  • PORT: The port where your database server is running (typically 27017 for MongoDB)
  • DATABASE: The name of the database

As an example, for a MongoDB database hosted on MongoDB Atlas, the connection URL might look similar to this:

file path : /.env

DATABASE_URL="mongodb+srv://test:test@cluster0.ns1yp.mongodb.net/myFirstDatabase"

5. Manually define the schema

Defining the schema in Prisma is straightforward. You have a /prisma/schema.prisma where we define the models we want to use in our application. If you are using VSCode, I suggest downloading the Prisma VSCode Extension

file path : prisma/schema.prisma

datasource db {  
provider = "mongodb"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
email String @unique
name String?
birthYear Int?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}

We have defined a very simple User schema which :

  1. Automatically generates a unique user id .
  2. Has a unique email field
  3. A name field and a birthYear field are optional.
  4. createdAtand updatedAt will be automatically handled.

For more information check out the MongoDB schema reference.

6. Sync schema with database

Now that we have written our schema, we need to create those collections in our database. This is also automatically done in Prisma using the CLI tool. Enter this command :

$ npx prisma db push

Note : When prisma schema is updated you needs to invoke db push for each schema change.

Now that our database has been set up, we can use Prisma Studio to explore our collections. Use the following command :

$ npx prisma studio

7. Install and generate Prisma Client

To get started with Prisma Client, you need to install the @prisma/client package:

$ npm install @prisma/client
$ npx prisma generate

Notice that the install command automatically invokes prisma generate for you which reads your Prisma schema and generates a version of Prisma Client that is tailored to your models.

Note : Whenever you make changes to your Prisma schema in the future, you manually need to invoke prisma generate in order to accommodate the changes in your Prisma Client API.

8. Use Prisma Client in your NestJS services

You’re now able to send database queries with Prisma Client. If you want to learn more about building queries with Prisma Client, check out the API documentation.

When setting up your NestJS application, you’ll want to abstract away the Prisma Client API for database queries within a service. To get started, you can create a new PrismaService that takes care of instantiating PrismaClient and connecting to your database.

Inside the src directory, create a new file called prisma.service.ts and add the following code to it:

file path : src/prisma.service.ts

import { INestApplication, Injectable, OnModuleInit } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';

@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit {
async onModuleInit() {
await this.$connect();
}

async enableShutdownHooks(app: INestApplication) {
this.$on('beforeExit', async () => {
await app.close();
});
}
}

Next, you can write services that you can use to make database calls for the User model from your Prisma schema.

Still inside the src directory, Open file app.service.ts and add the following code to it:

file path : src/app.service.ts

import { Injectable } from '@nestjs/common';
import { PrismaService } from './prisma.service';
import { User } from '@prisma/client';

@Injectable()
export class AppService {
constructor(private prisma: PrismaService) {}

async createUser(userData): Promise<User>
{
const result = await this.prisma.user.create({data:
userData});
return result;
}
}

9. Implement your REST API routes in the main app controller

Finally, you’ll use the services you created in the previous sections to implement the different routes of your app. For the purpose of this guide, you’ll put all your routes into the already existing AppController class.

Replace the contents of the app.controller.ts file with the following code:

file path : src/app.controller.ts

import {
Controller,
Post,
Body,
} from '@nestjs/common';
import { AppService } from './app.service';
import { User as UserModel} from '@prisma/client';

@Controller('user')
export class AppController {
constructor(
private readonly appService: AppService,
) {}
@Post('data')
async signupUser(
@Body() userData: { name?: string; email: string; birthYear?: number}
): Promise<UserModel> {
return this.appService.createUser(userData);
}
}

This controller implements the following routes:

POST

  • user/data: Create a new user.

Body:

  • email: String (required): The email address of the user.
  • name: String (optional): The name of the user.
  • birthYear : number(optional): The birth year of the user.

Hit API through Postman or Thunder Client.

That’s it! Happy coding! :)

--

--