


How to use Nest.js to connect to MongoDB database in
node? The following article will introduce to you how the node framework Nest.js uses MongoDB. I hope it will be helpful to you!
When learning to connect Nest to a database, you will inevitably encounter the problem of selecting a database. Here the author chose MongoDB
to record the simple use. You can choose the appropriate database according to different needs.
Post follow-up documents to facilitate further learningNest Chinese Documents,MongoDB Newbie Tutorial
##Database Introduction
- 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 a relational database and a non-relational database. It is the most feature-rich among non-relational databases and is most like a relational database.
- There are many mature databases on the market for everyone to choose from.
- According to various materials, the author concluded that
- PostgreSql
should be used for large projects and
for small projects. MongoDBSo the author is going to learn together. This time because I want to do a small project to practice my skills, I will use
MongoDBfirst to see how it goes.
If you have different opinions, please feel free to discuss them in the comment area.
- Make sure the computer has installed
MongoDB
No
- remember After finishing the environment configuration, you can start it automatically after booting, or you can choose to start it by yourself. Hahh, it depends on my personal
- . Let me give you a brief introduction.
Mongoose
is a
Nodejsdriver library that operates
MongoDB - ##MongoDB
is a database,
Nodejs
is a running environment for js.Nodejs
does not directly operateMongodb
. At this time, a corresponding driver is needed to provide an interface. Install the dependencies in the Nest project, there are two installation methods, choose by yourself -
$ npm install --save @nestjs/mongoose mongoose // NPM 安装 $ yarn add @nestjs/mongoose mongoose // YARN 安装复制代码
After the installation is completed, we will introduce it in the AppModule file Let’s take a look /* app.module.ts */ import { Module } from '@nestjs/common'; import { AppController } from './app.controller'; import { AppService } from './app.service'; // 我自己准备的 USER 模块 import { UserModule } from './user/user.module'; // 引入 Mongoose import { MongooseModule } from '@nestjs/mongoose'; @Module({ // 用 forRoot 方法连接数据库 imports: [UserModule, MongooseModule.forRoot('mongodb://localhost/test')], controllers: [AppController], providers: [AppService], }) export class AppModule {}
Basic functional module
- Here a User module is used for demo
- Here The basic functional modules I understand include
- module
(module)
Controller
(controller)Service
(provider)Schema
(data model) We mainly useNest to add, delete, modify and check
MongoDB
. These modules are currently sufficient. Let’s give a brief introduction to these modules:
- Because We have introduced the root module of app.module.ts above
- mongoose
So let’s take a look at what the functional module looks like
Schema
- In
- Mongoose
, everything originates from
Scheme
, and each Schema will be mapped toMongoDB
A collection and defines the structure of the documents within the collection.Schema
is used to define the model, and the model is responsible for creating and readingMongoDB
documents from the bottom layer. - Schema
You can use the built-in decorator of
NestJS
to create it, or you can use it yourselfMongoose
Normal way
. Using decorators to create Schema will greatly reduce references and improve code readability. The author here uses the official recommended method to create it with a decorator. After all, I am using Nest and I am not allowed to use something special hhh./* user.schema.ts */ import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; // @Prop 装饰器接受一个可选的参数,通过这个,你可以指示这个属性是否是必须的,是否需要默认值,或者是标记它作为一个常量,下面是例子 // SchemaFactory 是 mongoose 内置的一个方法做用是读取模式文档 并创建 Schema 对象 import { Document } from 'mongoose'; export type UserDocument = User & Document; @Schema() export class User extends Document { @Prop() name: string; // 设置值为必填 @Prop({ required: true }) age: number; @Prop() height: number; } export const UserSchema = SchemaFactory.createForClass(User);
- It will be introduced in Module together with other functions later.
Service
-
控制器的目的是接收应用的特定请求。路由机制控制哪个控制器接收哪些请求。通常,每个控制器有多个路由,不同的路由可以执行不同的操作。
/* 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'; @Injectable() export class UserService { // 注册Schema后,可以使用 @InjectModel() 装饰器将 User 模型注入到 UserService 中: constructor(@InjectModel('User') private userTest: Model<UserDocument>) {} // 添加 async create(createUserDto: CreateUserDto): Promise<User> { const createUser = new this.userTest(createUserDto); const temp = await createUser.save(); return temp; } // 查找 async findAll(): Promise<User[]> { // 这里是异步的 const temp = await this.userTest.find().exec(); return temp; } // 查找 async findOne(name: string): Promise<User[]> { // 这里是异步的 const temp = await this.userTest.find({ name }); return temp; } // 删除 async delete(sid: number) { // 这里是异步的 remove 方法删除成功并返回相应的个数 const temp = await this.userTest.remove({ _id: sid }); return temp; } // 修改 async updateUser(sid: string, data: any) { // 这里是异步的 remove 方法删除成功并返回相应的个数 const temp = await this.userTest.updateOne({ _id: sid }, { $set: data }); return temp; } }
等下和其他功能一起在 Module 中引入。
Controller
-
控制器的目的是接收应用的特定请求。路由机制控制哪个控制器接收哪些请求。通常,每个控制器有多个路由,不同的路由可以执行不同的操作。
/* user.controller.ts */ // 引入 Nest.js 内置的各个功能 import { Body, Controller, Delete, Get, Param, Post, Put, Query } from '@nestjs/common'; // 引入用户服务 import { UserService } from './user.service'; // 引入创建用户 DTO 用于限制从接口处传来的参数 import { CreateUserDto } from './user.dto'; // 配置局部路由 @Controller('user') export class UserController { constructor(private readonly userService: UserService) {} // 创建user路由 user/createUser @Post('createUser') async createUser(@Body() body: CreateUserDto) { return this.userService.create(body); } //查找所有 user 路由 @Get('findAll') async findAll() { return this.userService.findAll(); } // 查找某一个用户路由 @Get('findOne') async findOne(@Query() query: any) { return this.userService.findOne(query.name); } // 删除一个用户的路由 @Delete(':sid') deleteUser(@Param() param: any) { return this.userService.delete(param.sid); } // 更改用户信息的路由 @Put(':sid') updateUser(@Body() body: any, @Param() param: any) { return this.userService.updateUser(param.sid, body); } }
Moudle
模块是具有
@Module()
装饰器的类。@Module()
装饰器提供了元数据,Nest 用它来组织应用程序结构。-
我们把以上内容引入到我们的 User 模块中
/* 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提供了forFeature()方法来配置模块,包括定义哪些模型应该注册在当前范围中。 // 如果你还想在另外的模块中使用这个模型,将MongooseModule添加到CatsModule的exports部分并在其他模块中导入CatsModule。 // 这里的 name:'User' 为数据库表名称与 service 中注入的表名称对应两者不一样会报错 imports: [MongooseModule.forFeature([{ name: 'User', schema: UserSchema }])], controllers: [UserController], providers: [UserService], }) export class UserModule {}
- 以上我们的基础布局完成,可以进行接口检验了
接口检验
- 处理这些配置我们还在 main.ts 文件中配置了全局路由
app.setGlobalPrefix('api');
意思就是所有请求前面会有一个/api/
- 这里我们用的
PostMan
和MongoDB Compass
官方推荐的可视化工具查看效果
POST 增
这里我使用
POST
请求,路由为/api/user/createUser
因为要限制请求参数的数据类型所以这里方式为application/json
因为这里我们之前定义的 User 数据模型为 name,age,height, 所以请求里面只需要这几个参数即可,别的就算写进去也添加不到集合中
Postman
打开 MongoDB Compass 查看数据
可以看到我们已经添加到数据库中一条数据,接下来我们在添加两条,方便等会的查询/删除/更改操作
GET 查所有
这里我使用
GET
请求,,路由为/api/user/findAll
因为这里是查 User 集合内所有数据,所以不用添加请求参数-
Postman
打开 MongoDB Compass 查看数据
可以看到我们已经查询到数据库中刚才在
User
集合中添加的三条数据切记要点REFRESH
建不然软件不会自己刷新
GET 查单个用户
这里我使用
GET
请求,路由为/api/user/findOne
因为这里是查 User 集合内对应搜索条件的数据集合,这里我们用的是name 去查询的。也可以用唯一值 id 去查询。Postman
可以看到返回结果是一个集合,了解更多查询方式可以看下官网
PUT 改
这里我使用
PUT
请求,路由为/api/user/:sid
因为要限制请求参数的数据类型所以这里方式为application/json
因为这里我们之前定义的 User 数据模型为 age,height, 所以请求里面只需要这几个参数即可,别的就算写进去也添加不到集合中,我们这里传入数据库中小明的_id
61eea1b4144ea374a5b8455a
传入Param
中 ,然后把要修改的内容放入Body
中-
Postman
打开 MongoDB Compass 查看数据
可以看到我们已经把小明的年龄与身高做了修改
DELETE Delete
Here I use
DELETE
to request, and the route is/api/user/:sid
Because we need to limit the data type of request parameters, the method here isapplication/json
We pass in Xiao Ming’s _id in the database
61eea1b4144ea374a5b8455a
Pass inParam
and initiate a requestPostman
Open MongoDB Compass to view the data
- ##You can see that Xiao Ming’s information no longer exists
- So far we have completed using
- Mongoose
to
MongoDB data in Nest.jsbasic operations. And finished using decorators to create data model
Schemain Nest.
Looking at the document, it seems that you can also use the built-in - TypeORM in Nest to create models. Friends who are interested can take a look. When I go back to learn other database connections, I will read it and see how to operate it. There is still a lot to learn about Nest, such as pipelines, middleware, interceptors, routing guards, etc. I plan to use these in writing small demos to deepen my personal understanding. Otherwise, it is difficult to just read the documentation. Understood, I won’t go into details here~ What I know so far is that it is very popular to use pipelines to determine request types hhh Interested friends can learn about
- Class Validator
nodejs tutorial!
The above is the detailed content of Let's talk about how to use Nest.js to connect to MongoDB database in node. For more information, please follow other related articles on the PHP Chinese website!

node、nvm与npm的区别:1、nodejs是项目开发时所需要的代码库,nvm是nodejs版本管理工具,npm是nodejs包管理工具;2、nodejs能够使得javascript能够脱离浏览器运行,nvm能够管理nodejs和npm的版本,npm能够管理nodejs的第三方插件。

Vercel是什么?本篇文章带大家了解一下Vercel,并介绍一下在Vercel中部署 Node 服务的方法,希望对大家有所帮助!

node怎么爬取数据?下面本篇文章给大家分享一个node爬虫实例,聊聊利用node抓取小说章节的方法,希望对大家有所帮助!

node导出模块的两种方式:1、利用exports,该方法可以通过添加属性的方式导出,并且可以导出多个成员;2、利用“module.exports”,该方法可以直接通过为“module.exports”赋值的方式导出模块,只能导出单个成员。

安装node时会自动安装npm;npm是nodejs平台默认的包管理工具,新版本的nodejs已经集成了npm,所以npm会随同nodejs一起安装,安装完成后可以利用“npm -v”命令查看是否安装成功。

node中没有包含dom和bom;bom是指浏览器对象模型,bom是指文档对象模型,而node中采用ecmascript进行编码,并且没有浏览器也没有文档,是JavaScript运行在后端的环境平台,因此node中没有包含dom和bom。

本篇文章带大家聊聊Node.js中的path模块,介绍一下path的常见使用场景、执行机制,以及常用工具函数,希望对大家有所帮助!


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

Atom editor mac version download
The most popular open source editor

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver Mac version
Visual web development tools
