Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Nest.js to connect to MongoDB database in node

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

How to use Nest.js to connect to MongoDB database in node. For this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.

When learning Nest to connect with the database, it is inevitable to encounter the problem of choosing the database. Here the author chooses MongoDB to record the simple use. You can choose the appropriate database according to different needs.

Brief introduction of database

MongoDB is a database based on distributed file storage. Written in C++ language. Designed to provide scalable high-performance data storage solutions for WEB applications.

MongoDB is a product between relational database and non-relational database, which is the most functional and most like relational database in non-relational database.

Database selection

At present, there are many mature databases available for everyone to choose from.

According to looking through all kinds of materials, the author has come to the conclusion that PostgreSql is used for large projects and MongoDB is used for small projects, so the author is going to learn together. This time, because he wants to do a small project to practice, he will first use MongoDB to see how it is.

You are welcome to discuss it in the comments section if you have different views.

Configure basic servic

Make sure the computer has MongoDB installed.

Remember to configure the environment after you finish it, you can boot automatically, or you can choose to start your own hhh to see the individual.

Mongoose

Briefly, Mongoose is a Nodejs driver library that operates MongoDB.

MongoDB is a database, Nodejs is a running environment of js, Nodejs does not directly operate Mongodb, so the corresponding driver is needed to provide the interface.

Install dependencies in the Nest project. Choose the two installation methods.

$npm install-- save @ nestjs/mongoose mongoose / / NPM installation $yarn add @ nestjs/mongoose mongoose / / YARN installation copy code

After the installation is complete, let's introduce it into the AppModule file

/ * app.module.ts * / import {Module} from'@ nestjs/common';import {AppController} from'. / app.controller';import {AppService} from'. / app.service';// my own USER module import {UserModule} from'. / user/user.module';// introduces Mongoose import {MongooseModule} from'@ nestjs/mongoose' @ Module ({/ / use forRoot method to connect database imports: [UserModule, MongooseModule.forRoot ('mongodb://localhost/test')], controllers: [AppController], providers: [AppService],}) export class AppModule {} basic function module

Here we use a User module to do demo

The basic functional modules I understand here include module (module) Controller (controller) Service (provider) Schema (data model) We mainly use Nest to add, delete, modify and check MongoDB. These modules are available for the time being.

Give a brief introduction to these modules:

Since we have already introduced mongoose to the root module of app.module.ts, let's take a look at what the functional module looks like.

Schema

In Mongoose, everything originates from Scheme, and each Schema maps to a collection of MongoDB and defines the structure of the documents within the collection. Schema is used to define the model, which is responsible for creating and reading MongoDB documents from the underlying.

Schema can be created using NestJS's built-in decorator, or you can do it yourself in the usual way of Mongoose. Using decorators to create Schema greatly reduces references and improves the readability of your code. Here the author uses the official recommendation to use the decorator to create, after all, the use of Nest can not use some features of the hhh.

/ * user.schema.ts * / import {Prop, Schema, SchemaFactory} from'@ nestjs/mongoose'; / / @ Prop decorator accepts an optional parameter, through which you can indicate whether this property is required, whether a default value is required, or mark it as a constant. The following example / / SchemaFactory is a built-in method for mongoose to read the schema document and create the Schema object import {Document} from 'mongoose' Export type UserDocument = User & Document; @ Schema () export class User extends Document {@ Prop () name: string; / / is required @ Prop ({required: true}) age: number; @ Prop () height: number;} export const UserSchema = SchemaFactory.createForClass (User)

It will be introduced in Module later along with other features.

Service

The purpose of the controller is to receive specific requests from the application. The routing mechanism controls which controller receives which requests. Typically, each controller has multiple routes, and different routes can perform different operations.

/ * user.service.ts * / import {Model} from 'mongoose'; import {InjectModel} from' @ nestjs/mongoose'; import {User, UserDocument} from 'src/schema/user.schema'; import {CreateUserDto} from'. / user.dto' After @ Injectable () export class UserService {/ / registers the Schema, you can use the @ InjectModel () decorator to inject the User model into the UserService: constructor (@ InjectModel ('User') private userTest: Model) {} / / add async create (createUserDto: CreateUserDto): Promise {const createUser = new this.userTest (createUserDto); const temp = await createUser.save () Return temp;} / / find async findAll (): Promise {/ / here is the asynchronous const temp = await this.userTest.find (). Exec (); return temp } / / find async findOne (name: string): Promise {/ / here is asynchronous const temp = await this.userTest.find ({name}); return temp } / / Delete async delete (sid: number) {/ / here is the asynchronous remove method deleted successfully and returned the corresponding number const temp = await this.userTest.remove ({_ id: sid}); return temp } / / modify async updateUser (sid: string, data: any) {/ / here is the asynchronous remove method deleted successfully and returned the corresponding number const temp = await this.userTest.updateOne ({_ id: sid}, {$set: data}); return temp;}}

It will be introduced in Module later along with other features.

Controller

The purpose of the controller is to receive specific requests from the application. The routing mechanism controls which controller receives which requests. Typically, each controller has multiple routes, and different routes can perform different operations.

/ * user.controller.ts * / / introduce various built-in functions of Nest.js import {Body, Controller, Delete, Get, Param, Post, Put, Query} from'@ nestjs/common'; / / introduce user service import {UserService} from'. / user.service'; / / introduce the creation of user DTO to restrict the parameter import {CreateUserDto} from'. / user.dto' coming from the interface / / configure local route @ Controller ('user') export class UserController {constructor (private readonly userService: UserService) {} / / create user route user/createUser @ Post (' createUser') async createUser (@ Body () body: CreateUserDto) {return this.userService.create (body) } / / find all user routes @ Get ('findAll') async findAll () {return this.userService.findAll ();} / find a user route @ Get (' findOne') async findOne (@ Query () query: any) {return this.userService.findOne (query.name) } / / Delete a user's route @ Delete (': sid') deleteUser (@ Param () param: any) {return this.userService.delete (param.sid) } / / change the route of user information @ Put (': sid') updateUser (@ Body () body: any, @ Param () param: any) {return this.userService.updateUser (param.sid, body);}} Moudle

A module is a class with a @ Module () decorator. The @ Module () decorator provides metadata, which Nest uses to organize the application structure.

We introduce the above into our User module

/ * user.module.ts * / import {Module} from'@ nestjs/common'; import {UserController} from'. / user.controller'; import {UserService} from'. / user.service'; import {MongooseModule} from'@ nestjs/mongoose'; import {UserSchema} from 'src/schema/user.schema'; @ Module ({/ / MongooseModule provides forFeature () methods to configure modules, including defining which models should be registered in the current scope. / / if you want to use this model in another module, add MongooseModule to the exports section of CatsModule and import CatsModule in other modules. / / the name:'User' here indicates that the database table name corresponds to the table name injected in service. The error imports will be reported: [MongooseModule.forFeature ([{name:'User', schema: UserSchema}])], controllers: [UserController], providers: [UserService],}) export class UserModule {}

The above basic layout is complete, and we can verify the interface.

Interface check

To handle these configurations, we have also configured the global routing app.setGlobalPrefix ('api') in the main.ts file; it means that all requests will be preceded by a / api/

Here we use the visualization tools officially recommended by PostMan and MongoDB Compass to view the results.

POST increase

Here I use the POST request, which is routed to / api/user/createUser because I want to limit the data type of the request parameter, so the method here is application/json

Because the User data model we defined here is name,age,height, only these parameters are needed in the request, and nothing else can be added to the collection even if written in.

Postman

Open MongoDB Compass to view data

You can see that we have added one piece of data to the database, and then we will add two items to facilitate the query / delete / change operation later.

GET, check everything.

Here I use the GET request, which is routed to / api/user/findAll because it looks up all the data in the User collection, so there is no need to add request parameters

Postman

Open MongoDB Compass to view data

You can see that we have queried the three pieces of data that we just added to the User collection in the database. Remember that REFRESH is built, or the software will not refresh itself.

GET looks up a single user

Here I use the GET request, which is routed to / api/user/findOne because here we look up the data set corresponding to the search criteria in the User collection, and here we use name to query. You can also query with a unique value of id.

Postman

You can see that the returned result is a collection. For more information on query methods, please take a look at the official website.

PUT reform

Here I use the PUT request, which is routed to / api/user/:sid because I want to limit the data type of the request parameter, so the method here is application/json

Because the User data model we defined earlier is age,height, we only need these parameters in the request, and other parameters cannot be added to the collection even if they are written in. We pass the _ id 61eea1b4144ea374a5b8455a of the database into the Param here, and then put the content to be modified into the Body.

Postman

Open MongoDB Compass to view data

We can see that we have changed Xiao Ming's age and height.

DELETE deletion

Here I use the DELETE request, which is routed to / api/user/:sid because I want to limit the data type of the request parameter, so the method here is application/json

The _ id 61eea1b4144ea374a5b8455a of the database is passed into the Param and the request is initiated.

Postman

Open MongoDB Compass to view data

You can see that Xiaoming's information no longer exists.

Summary

At this point, we have completed the basic operation of using Mongoose on MongoDB data in Nest.js. And completed the use of decorators in Nest to create the data model Schema.

It seems that the document can also use the built-in TypeORM in Nest to create a model. Interested partners can take a look at it. When I go back to learn about other database connections, I will look through it and see how to operate it.

Nest still has a lot to learn, pipes, middleware, interceptors, routing guards and so on. I am going to use these in writing small demo to deepen personal understanding, otherwise it is difficult to understand simply looking at the documentation. I will not repeat it here. What I know at present is that using pipes to determine the type of request is very fragrant. Hhh interested partners can learn about the next class verifier.

This is the answer to the question about how to use Nest.js to connect to the MongoDB database in node. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel to learn more about it.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report