NestJS has emerged as one of the go-to frameworks for building modern server-side applications in Node.js. With its rich features and TypeScript integration, developers love using it for various applications. One of the most popular databases for application development today is MongoDB, especially when combined with Mongoose. In this guide, we'll see how to effectively work with MongoDB using Mongoose in a NestJS context.
First, make sure you have Node.js installed on your machine. If you haven't already, you can create a new NestJS project using the command-line interface. For this example, we'll name our project nest-mongo-demo
.
npm install -g @nestjs/cli nest new nest-mongo-demo cd nest-mongo-demo
Once your NestJS project is set up, you can install Mongoose. Run the following command in your terminal:
npm install mongoose @nestjs/mongoose
We'll also utilize the @types/mongoose
package for TypeScript support:
npm install --save-dev @types/mongoose
Now that we have the necessary packages installed, we’ll configure our NestJS application to connect to MongoDB. This can be done in the app.module.ts
file.
Open src/app.module.ts
and import the MongooseModule
. Update the imports
array with the Mongoose connection configuration.
import { Module } from '@nestjs/common'; import { MongooseModule } from '@nestjs/mongoose'; @Module({ imports: [ MongooseModule.forRoot('mongodb://localhost/nest'), ], }) export class AppModule {}
This code connects your application to a MongoDB database named nest
on your local machine. Replace the connection string with your own if you're using a cloud service like MongoDB Atlas.
Next, we need to define a schema for our MongoDB collection using Mongoose. Let's say we are building a simple application to manage users. Create a new directory named user
inside src
, and create a file named user.schema.ts
inside it.
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Document } from 'mongoose'; export type UserDocument = User & Document; @Schema() export class User { @Prop({ required: true }) name: string; @Prop() age: number; @Prop() email: string; } export const UserSchema = SchemaFactory.createForClass(User);
Here, we define a User
schema with three fields: name
, age
, and email
. The @Prop()
decorator is used to define the properties of our schema.
We need a service to encapsulate the business logic for our user management. Create a user.service.ts
file in the user
directory.
import { Injectable } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import { User, UserDocument } from './user.schema'; @Injectable() export class UserService { constructor(@InjectModel(User.name) private userModel: Model<UserDocument>) {} async create(createUserDto: Partial<User>): Promise<User> { const user = new this.userModel(createUserDto); return user.save(); } async findAll(): Promise<User[]> { return this.userModel.find().exec(); } }
Here we use the @InjectModel()
decorator to inject our user model into the service. The create
method allows adding new users, while findAll
fetches all users from the database.
Next, we create a controller to handle incoming requests related to users. Add a user.controller.ts
file in the user
directory.
import { Body, Controller, Get, Post } from '@nestjs/common'; import { UserService } from './user.service'; import { User } from './user.schema'; @Controller('users') export class UserController { constructor(private readonly userService: UserService) {} @Post() create(@Body() createUserDto: Partial<User>) { return this.userService.create(createUserDto); } @Get() findAll() { return this.userService.findAll(); } }
This controller defines two routes: a POST route to create a new user and a GET route to fetch all users.
Now that we have created our controller and service, we need to register them in a module. Update or create user.module.ts
in the user
directory:
import { Module } from '@nestjs/common'; import { MongooseModule } from '@nestjs/mongoose'; import { User, UserSchema } from './user.schema'; import { UserService } from './user.service'; import { UserController } from './user.controller'; @Module({ imports: [MongooseModule.forFeature([{ name: User.name, schema: UserSchema }])], controllers: [UserController], providers: [UserService], }) export class UserModule {}
Finally, don’t forget to import the UserModule
into your AppModule
.
import { Module } from '@nestjs/common'; import { MongooseModule } from '@nestjs/mongoose'; import { UserModule } from './user/user.module'; @Module({ imports: [ MongooseModule.forRoot('mongodb://localhost/nest'), UserModule, ], }) export class AppModule {}
You can now run your NestJS application:
npm run start
Your application is now set up to handle user data with MongoDB. You can interact with your API using tools like Postman or Insomnia. For example, to create a new user, you would send a POST request to http://localhost:3000/users
with a JSON body like:
{ "name": "John Doe", "age": 30, "email": "john@example.com" }
You can retrieve all users with a simple GET request to http://localhost:3000/users
.
By following the steps outlined above, you have successfully created a simple NestJS application integrated with MongoDB using Mongoose. You can further expand functionality by adding other operations like updating and deleting users, as well as adding validation, authentication, and authorization, thereby enhancing your NestJS backend development experience.
10/12/2024 | NestJS
10/12/2024 | NestJS
10/12/2024 | NestJS
10/12/2024 | NestJS
10/12/2024 | NestJS
10/12/2024 | NestJS
10/12/2024 | NestJS
10/12/2024 | NestJS