I recently started learning the NestJs framework. The learning cost is much higher than other frameworks. 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) It can be seen as an object in NestJs This makes it very simple to operate on each table in the database. 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
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 Then inject the model (Schema) 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.) 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
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') 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 Got the result 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:
|
<<: Detailed explanation of keywords and reserved words in MySQL 5.7
>>: A brief discussion on the preliminary practice of Docker container interconnection
nvm nvm is responsible for managing multiple vers...
In some scenarios, we need to modify our varchar ...
<br />Once, Foyin and Mr. Dongpo were chatti...
I recently reviewed some CSS-related knowledge po...
Nowadays, application development is basically se...
Please open the test page in a mainstream browser...
Let me briefly explain the functional scenario: T...
Table of contents MySQL federated query execution...
When position is absolute, the percentage of its ...
Table of contents Query cache optimization Overvi...
Installing Docker on CentOS requires the operatin...
Previously, https://www.jb51.net/article/205922.h...
Due to the default bridge network, the IP address...
Method 1: var a = [1,2,3]; var b=[4,5] a = a.conc...
In HTML pages, visual elements such as buttons an...