Table of Contents
Service
Controller
Moudle
接口检验
POST 增
GET 查所有
GET 查单个用户
PUT 改
DELETE Delete
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

Jan 26, 2022 pm 05:52 PM
mongodb node database

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 安装复制代码
    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 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);
    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(&#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;
              }
        }
    Copy after login
  • 等下和其他功能一起在 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);
          }
        }
    Copy after login

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 {}
    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, 所以请求里面只需要这几个参数即可,别的就算写进去也添加不到集合中,我们这里传入数据库中小明的_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 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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

How to configure MongoDB automatic expansion on Debian How to configure MongoDB automatic expansion on Debian Apr 02, 2025 am 07:36 AM

This article introduces how to configure MongoDB on Debian system to achieve automatic expansion. The main steps include setting up the MongoDB replica set and disk space monitoring. 1. MongoDB installation First, make sure that MongoDB is installed on the Debian system. Install using the following command: sudoaptupdatesudoaptinstall-ymongodb-org 2. Configuring MongoDB replica set MongoDB replica set ensures high availability and data redundancy, which is the basis for achieving automatic capacity expansion. Start MongoDB service: sudosystemctlstartmongodsudosys

How to ensure high availability of MongoDB on Debian How to ensure high availability of MongoDB on Debian Apr 02, 2025 am 07:21 AM

This article describes how to build a highly available MongoDB database on a Debian system. We will explore multiple ways to ensure data security and services continue to operate. Key strategy: ReplicaSet: ReplicaSet: Use replicasets to achieve data redundancy and automatic failover. When a master node fails, the replica set will automatically elect a new master node to ensure the continuous availability of the service. Data backup and recovery: Regularly use the mongodump command to backup the database and formulate effective recovery strategies to deal with the risk of data loss. Monitoring and Alarms: Deploy monitoring tools (such as Prometheus, Grafana) to monitor the running status of MongoDB in real time, and

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

Navicat's method to view MongoDB database password Navicat's method to view MongoDB database password Apr 08, 2025 pm 09:39 PM

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

How to encrypt data in Debian MongoDB How to encrypt data in Debian MongoDB Apr 12, 2025 pm 08:03 PM

Encrypting MongoDB database on a Debian system requires following the following steps: Step 1: Install MongoDB First, make sure your Debian system has MongoDB installed. If not, please refer to the official MongoDB document for installation: https://docs.mongodb.com/manual/tutorial/install-mongodb-on-debian/Step 2: Generate the encryption key file Create a file containing the encryption key and set the correct permissions: ddif=/dev/urandomof=/etc/mongodb-keyfilebs=512

What is the CentOS MongoDB backup strategy? What is the CentOS MongoDB backup strategy? Apr 14, 2025 pm 04:51 PM

Detailed explanation of MongoDB efficient backup strategy under CentOS system This article will introduce in detail the various strategies for implementing MongoDB backup on CentOS system to ensure data security and business continuity. We will cover manual backups, timed backups, automated script backups, and backup methods in Docker container environments, and provide best practices for backup file management. Manual backup: Use the mongodump command to perform manual full backup, for example: mongodump-hlocalhost:27017-u username-p password-d database name-o/backup directory This command will export the data and metadata of the specified database to the specified backup directory.

See all articles