Home >Web Front-end >JS Tutorial >Let's talk about how to use Nest.js to connect to MongoDB database in node

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

青灯夜游
青灯夜游forward
2022-01-26 17:52:283937browse

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 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.

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
  • PostgreSql should be used for large projects and for small projects. MongoDB So the author is going to learn together. This time because I want to do a small project to practice my skills, I will use MongoDB first 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

    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

Mongoose

  • . Let me give you a brief introduction.

    Mongoose is a Nodejs driver library that operates MongoDB

  • ##MongoDB

    is a database,Nodejs is a running environment for js. Nodejs does not directly operate Mongodb. 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 use Nest to add, delete, modify and check MongoDB. 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 from Scheme, and each Schema will be mapped to MongoDB 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 reading MongoDB documents from the bottom layer.

  • Schema

    You can use the built-in decorator of NestJS to create it, or you can use it yourself MongooseNormal 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(&#39;User&#39;) 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 &#39;@nestjs/common&#39;;
        // 引入用户服务
        import { UserService } from &#39;./user.service&#39;;
        // 引入创建用户 DTO 用于限制从接口处传来的参数
        import { CreateUserDto } from &#39;./user.dto&#39;;
        // 配置局部路由
        @Controller(&#39;user&#39;)
        export class UserController {
          constructor(private readonly userService: UserService) {}
          // 创建user路由 user/createUser
          @Post(&#39;createUser&#39;)
          async createUser(@Body() body: CreateUserDto) {
            return this.userService.create(body);
          }
          //查找所有 user 路由
          @Get(&#39;findAll&#39;)
          async findAll() {
            return this.userService.findAll();
          }
          // 查找某一个用户路由
          @Get(&#39;findOne&#39;)
          async findOne(@Query() query: any) {
            return this.userService.findOne(query.name);
          }
          // 删除一个用户的路由
          @Delete(&#39;:sid&#39;)
          deleteUser(@Param() param: any) {
            return this.userService.delete(param.sid);
          }
          // 更改用户信息的路由
          @Put(&#39;:sid&#39;)
          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 &#39;@nestjs/common&#39;;
        import { UserController } from &#39;./user.controller&#39;;
        import { UserService } from &#39;./user.service&#39;;
        import { MongooseModule } from &#39;@nestjs/mongoose&#39;;
        import { UserSchema } from &#39;src/schema/user.schema&#39;;
        @Module({
           // MongooseModule提供了forFeature()方法来配置模块,包括定义哪些模型应该注册在当前范围中。
           // 如果你还想在另外的模块中使用这个模型,将MongooseModule添加到CatsModule的exports部分并在其他模块中导入CatsModule。
           // 这里的 name:&#39;User&#39; 为数据库表名称与 service 中注入的表名称对应两者不一样会报错
          imports: [MongooseModule.forFeature([{ name: &#39;User&#39;, schema: UserSchema }])],
          controllers: [UserController],
          providers: [UserService],
        })
        export class UserModule {}
    • 以上我们的基础布局完成,可以进行接口检验了

接口检验

  • 处理这些配置我们还在 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, 所以请求里面只需要这几个参数即可,别的就算写进去也添加不到集合中,我们这里传入数据库中小明的_id 61eea1b4144ea374a5b8455a 传入 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 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 is application/json

  • We pass in Xiao Ming’s _id in the database 61eea1b4144ea374a5b8455a Pass in Param and 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!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete