Let's talk about how to use Nest.js to connect to MongoDB database in node

青灯夜游
Release: 2022-01-26 17:52:28
forward
3727 people have browsed it

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!

Let's talk about how to use Nest.js to connect to MongoDB database in node

When learning to connect Nest to a database, you will inevitably encounter the problem of selecting a database. Here the author choseMongoDBto 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.

Database selection

    There are many mature databases on the market for everyone to choose from.

Lets talk about how to use Nest.js to connect to MongoDB database in node

    According to various materials, the author concluded that
  • PostgreSqlshould be used for large projects andfor 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 useMongoDBfirst to see how it goes.
  • If you have different opinions, please feel free to discuss them in the comment area.
Configure basic services

  • Make sure the computer has installed

    MongoDBNo

  • 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

Mongoose

  • . Let me give you a brief introduction.

    Mongooseis aNodejsdriver library that operatesMongoDB

  • ##MongoDB

    is a database,Nodejsis a running environment for js.Nodejsdoes 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 安装复制代码
    Copy after login

  • 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 {}
    Copy after login

  • 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 checkMongoDB. These modules are currently sufficient.

  • Let’s give a brief introduction to these modules:

Lets talk about how to use Nest.js to connect to MongoDB database in node

    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 fromScheme, and eachSchemawill be mapped toMongoDBA collection and defines the structure of the documents within the collection.Schemais used to define the model, and the model is responsible for creating and readingMongoDBdocuments from the bottom layer.

  • Schema

    You can use the built-in decorator ofNestJSto create it, or you can use it yourselfMongooseNormal way. Using decorators to createSchemawill 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);
    Copy after login
  • 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) {} // 添加 async create(createUserDto: CreateUserDto): Promise { const createUser = new this.userTest(createUserDto); const temp = await createUser.save(); return temp; } // 查找 async findAll(): Promise { // 这里是异步的 const temp = await this.userTest.find().exec(); return temp; } // 查找 async findOne(name: string): Promise { // 这里是异步的 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; } }
    Copy after login
  • 等下和其他功能一起在 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); } }
    Copy after login

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 {}
    Copy after login
    • 以上我们的基础布局完成,可以进行接口检验了

接口检验

  • 处理这些配置我们还在 main.ts 文件中配置了全局路由app.setGlobalPrefix('api');意思就是所有请求前面会有一个/api/
  • 这里我们用的PostManMongoDB Compass官方推荐的可视化工具查看效果

POST 增

  • 这里我使用POST请求,路由为/api/user/createUser因为要限制请求参数的数据类型所以这里方式为application/json

  • 因为这里我们之前定义的 User 数据模型为 name,age,height, 所以请求里面只需要这几个参数即可,别的就算写进去也添加不到集合中

  • Postman

Lets talk about how to use Nest.js to connect to MongoDB database in node

  • 打开 MongoDB Compass 查看数据

Lets talk about how to use Nest.js to connect to MongoDB database in node

  • 可以看到我们已经添加到数据库中一条数据,接下来我们在添加两条,方便等会的查询/删除/更改操作

GET 查所有

  • 这里我使用GET请求,,路由为/api/user/findAll因为这里是查 User 集合内所有数据,所以不用添加请求参数

  • Postman

    Lets talk about how to use Nest.js to connect to MongoDB database in node

  • 打开 MongoDB Compass 查看数据

Lets talk about how to use Nest.js to connect to MongoDB database in node

  • 可以看到我们已经查询到数据库中刚才在User集合中添加的三条数据切记要点REFRESH建不然软件不会自己刷新

GET 查单个用户

  • 这里我使用GET请求,路由为/api/user/findOne因为这里是查 User 集合内对应搜索条件的数据集合,这里我们用的是name 去查询的。也可以用唯一值 id 去查询。

  • Postman

Lets talk about how to use Nest.js to connect to MongoDB database in node

  • 可以看到返回结果是一个集合,了解更多查询方式可以看下官网

PUT 改

  • 这里我使用PUT请求,路由为/api/user/:sid因为要限制请求参数的数据类型所以这里方式为application/json

  • 因为这里我们之前定义的 User 数据模型为 age,height, 所以请求里面只需要这几个参数即可,别的就算写进去也添加不到集合中,我们这里传入数据库中小明的_id61eea1b4144ea374a5b8455a传入Param中 ,然后把要修改的内容放入Body

  • Postman

    Lets talk about how to use Nest.js to connect to MongoDB database in node

  • 打开 MongoDB Compass 查看数据

Lets talk about how to use Nest.js to connect to MongoDB database in node

  • 可以看到我们已经把小明的年龄与身高做了修改

DELETE Delete

  • Here I useDELETEto request, and the route is/api/user/:sidBecause we need to limit the data type of request parameters, the method here isapplication/json

  • We pass in Xiao Ming’s _id in the database61eea1b4144ea374a5b8455aPass inParamand initiate a request

  • Postman

Lets talk about how to use Nest.js to connect to MongoDB database in node

  • Open MongoDB Compass to view the data

1Lets talk about how to use Nest.js to connect to MongoDB database in node

  • ##You can see that Xiao Ming’s information no longer exists

Summary

For more node-related knowledge, please visit:

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!

Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!