NestJs uses Mongoose to operate MongoDB

NestJs uses Mongoose to operate MongoDB

I recently started learning the NestJs framework. The learning cost is much higher than other frameworks.
Its registration configuration is relatively complex and it is a bit confusing to learn at first; but this is also a reflection of its more standardized and rigorous nature compared to other frameworks. Ensures stable and robust use of large projects!

When learning the node basic framework Express and Koa. Database operations have always been implemented by writing SQL statements. Write whatever is needed. This seems very rigid and inflexible. Later, I learned that NestJs is OOP-oriented programming (NestJs can use TypeScript, which is also OOP-oriented), and then I realized that database operations can be expressed in the form of objects. Each table (Schema) in the database can be regarded as an object in the Nest framework. This makes database operations very flexible

For example: (This is the structure of an arbitrary table)

insert image description here

It can be seen as an object in NestJs

insert image description here

This makes it very simple to operate on each table in the database.
Here we take the link mongoDB operation as an example

Use mongoose according to the official documentation

First, install the required dependencies

npm install --save @nestjs/mongoose mongoose

You can add a Taobao mirror:

–registry=https://registry.npm.taobao.org

I have become very proficient at this and it is very convenient to use. The download speed will be much faster

After the installation is complete, we add configuration to app.module.ts

app.module.ts

insert image description here

Add the corresponding configuration in imports:[]

MongooseModule.forRoot('mongodb://localhost/test')
//The following is the location of MongoDB (depending on your needs)
Add corresponding dependencies import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';

After saving, you can see it in the console
DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect
Such a similar sentence. This means the link is successful.

Then inject the model (Schema)
Create schema folder in your corresponding module folder. Create xx.schema.ts

For example, mine is users/schemas/users.schema.ts

import * as mongoose from 'mongoose'

export const UserSchema = new mongoose.Schema(
  {
    id: Number,
    name: String,
    introduction: String,
    headurl: String,
    bigurl: String,
    username: String,
    password: String,
  },
  { collection: 'musicers', versionKey: false },
)

This corresponds to the table structure in the figure above (collection: can be regarded as a table in MongoDB.)
Next, add the configuration in the corresponding users.module.ts module

import { Module } from '@nestjs/common';
import { MongooseModule, getModelToken } from '@nestjs/mongoose';
import { UsersController } from './users.controller';
import { UsersService } from './services/users.service';
import { UserSchema } from './schemas/users.schemas';

@Module({
  imports: [
  //Add configuration here. Corresponding import module (pay attention to the bracket structure inside, don't let it get in the way. I got stuck here for a long time)
    MongooseModule.forFeature([
      { name: 'User', schema: UserSchema }
    ])
  ],
  controllers: [UsersController],
  providers:
    UsersService,
   ],
})
export class UsersModule {}

After this configuration. We can operate on the service side

Service => users/users.service.ts

Let's take a search to test

import { Model } from 'mongoose';
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { User } from '../interface/users.interface';
import { IUserService } from '../interface/user-service.interface';


@Injectable()
export class UsersService implements IUserService {

  constructor(@InjectModel('User') private readonly userModel: Model<User>) {}
  
  private static users:User[] = [ ]

  async findAll():Promise<User[]>{
    //return UsersService.users
    return await this.userModel.find({})
    //(Here we test to find all)
  }

}

Controller => users/users.controller.ts

@Controller('users')
export class UsersController {
  constructor(private readonly userservice: UsersService) { }

@Get('getall')
  // @UseGuards(AuthGuard('jwt'))
  async findAll():Promise<User[]> {
    return await this.userservice.findAll()
  }
}

We open an interface. Here 3001 is customized in main.ts. Change it according to your own situation and then we can access
http://localhost:3001/users/getall

insert image description here

Got the result

insert image description here

Output is complete. Other operations are performed according to similar steps.

This is the end of this article about how to use Mongoose with NestJs to operate MongoDB. For more information about how to operate MongoDB with NestJs, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Nest.js authorization verification method example
  • Detailed explanation of Nest.js environment variable configuration and serialization
  • How to use nest.js to provide multiple static directories using express

<<:  Detailed explanation of keywords and reserved words in MySQL 5.7

>>:  A brief discussion on the preliminary practice of Docker container interconnection

Recommend

Detailed installation process of nodejs management tool nvm

nvm nvm is responsible for managing multiple vers...

When modifying a record in MySQL, the update operation field = field + string

In some scenarios, we need to modify our varchar ...

Design Theory: A Method to Understand People's Hearts

<br />Once, Foyin and Mr. Dongpo were chatti...

Detailed explanation of CSS margin overlap and solution exploration

I recently reviewed some CSS-related knowledge po...

How to use skeleton screen in vue project

Nowadays, application development is basically se...

Measured image HTTP request

Please open the test page in a mainstream browser...

Some notes on mysql self-join deduplication

Let me briefly explain the functional scenario: T...

Detailed explanation of MySQL joint query optimization mechanism

Table of contents MySQL federated query execution...

Calculation of percentage value when the css position property is absolute

When position is absolute, the percentage of its ...

Detailed explanation of Mysql's concurrent parameter adjustment

Table of contents Query cache optimization Overvi...

Detailed steps to install docker in 5 minutes

Installing Docker on CentOS requires the operatin...

Implementation of mounting NFS shared directory in Docker container

Previously, https://www.jb51.net/article/205922.h...

Docker compose custom network to achieve fixed container IP address

Due to the default bridge network, the IP address...

JavaScript array merging case study

Method 1: var a = [1,2,3]; var b=[4,5] a = a.conc...

Detailed explanation of JavaScript onblur and onfocus events

In HTML pages, visual elements such as buttons an...