NestJS is a powerful Node.js framework that enables developers to build efficient, scalable, and maintainable server-side applications. When it comes to working with databases, MongoDB is a popular choice due to its flexibility and scalability. To interact with MongoDB in a NestJS application, one of the most commonly used libraries is Mongoose, which provides an elegant and straightforward way to define schemas, create models, and perform database operations. In this article, we will explore how to establish a MongoDB connection with Mongoose in a NestJS application and create a user using a practical example.
Prerequisites
Before we dive into the code, make sure you have the following prerequisites installed:
Node.js and npm: Ensure you have Node.js (along with npm, its package manager) installed on your machine.
NestJS CLI: Install the NestJS CLI globally using the following command:
npm install -g @nestjs/cli
- MongoDB: Make sure you have a MongoDB instance running locally or have access to a remote MongoDB server.
Setting up the NestJS Application
Let’s start by creating a new NestJS application. Open your terminal and run the following commands:
nest new nest-mongoose-example
cd nest-mongoose-example
This will generate a new NestJS project with the name nest-mongoose-example.
Installing Dependencies
In your project directory, install the necessary dependencies using the following commands:
npm install mongoose @nestjs/mongoose
- mongoose: The MongoDB library for Node.js.
- @nestjs/mongoose: The official NestJS package for integrating Mongoose.
Establishing the MongoDB Connection
In order to connect to MongoDB using Mongoose in a NestJS application, you need to set up a module to manage the connection. Let’s create a database.module.ts file inside the src folder with the following content:
// database.module.ts
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
@Module({
imports: [
MongooseModule.forRoot('mongodb://localhost/nest-mongoose-example'),
],
})
export class DatabaseModule {}
In this module, we use the MongooseModule.forRoot() method to establish the connection to the MongoDB instance. Adjust the connection URL (mongodb://localhost/nest-mongoose-example) according to your MongoDB configuration.
Creating a User Schema and Model
Next, let’s create a user schema and model using Mongoose. Create a new file named user.schema.ts inside the src folder with the following code:
// user.schema.ts
import * as mongoose from 'mongoose';
export const UserSchema = new mongoose.Schema({
firstName: String,
lastName: String,
email: String,
});
export interface User extends mongoose.Document {
firstName: string;
lastName: string;
email: string;
}
This schema defines the structure of a user document in MongoDB.
Creating a User Service
Now that we have the schema and model in place, let’s create a service to interact with the database. Create a user.service.ts file inside the src folder with the following content:
// user.service.ts
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { User } from './user.schema';
@Injectable()
export class UserService {
constructor(@InjectModel('User') private readonly userModel: Model<User>) {}
async createUser(firstName: string, lastName: string, email: string): Promise<User> {
const newUser = new this.userModel({ firstName, lastName, email });
return newUser.save();
}
}
The UserService class uses the InjectModel decorator from @nestjs/mongoose to inject the User model into the service. The createUser method takes user information as input and creates a new user in the database.
Creating a User Controller
To expose the user creation functionality as an API endpoint, let’s create a controller. Create a user.controller.ts file inside the src folder with the following code:
// user.controller.ts
import { Controller, Post, Body } from '@nestjs/common';
import { UserService } from './user.service';
@Controller('users')
export class UserController {
constructor(private readonly userService: UserService) {}
@Post()
async createUser(@Body() body: any) {
const { firstName, lastName, email } = body;
return this.userService.createUser(firstName, lastName, email);
}
}
In this controller, we define a POST endpoint at the /users route. When a POST request is made to this route with user data in the request body, the createUser method from the UserService is called to create a new user.
Wiring Everything Together
Finally, let’s wire up the modules and components in the app.module.ts file:
// app.module.ts
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { DatabaseModule } from './database.module';
import { UserController } from './user.controller';
import { UserService } from './user.service';
import { UserSchema } from './user.schema';
@Module({
imports: [DatabaseModule, MongooseModule.forFeature([{ name: 'User', schema: UserSchema }])],
controllers: [UserController],
providers: [UserService],
})
export class AppModule {}
In this file, we import the necessary modules, controllers, services, and schemas. We use the MongooseModule.forFeature() method to import the User model into the module.
Testing the User Creation
To test the user creation functionality, start your NestJS application using the following command:
npm run start:dev
Assuming your server is running locally on port 3000, you can use a tool like curl, Postman, or your preferred API client to make a POST request to http://localhost:3000/users with the following JSON body:
{
"firstName": "John",
"lastName": "Doe",
"email": "john.doe@example.com"
}
You should receive a response containing the newly created user document.
Conclusion
In this article, we walked through the process of establishing a MongoDB connection using Mongoose in a NestJS application. We created a user schema, model, service, and controller to perform a user creation operation using a REST API endpoint. NestJS, Mongoose, and MongoDB provide a powerful stack for building efficient and scalable server-side applications, making it a popular choice for developers.
Top comments (0)