nestjs的一个简单模板

nest js 英文官网 NestJS - A progressive Node.js framework

nestjs 中文网  NestJS 简介 | NestJS 中文文档 | NestJS 中文网

nestjs 中文网2  Nest.js 中文文档

以上是三个自学文档 

连接mongodb

 /* app.module.ts */
 import { Module, Options } from '@nestjs/common';
 import { AppController } from './app.controller';
 import { AppService } from './app.service';
 import { UserModule } from './user/user.module';
 // 引入 Mongoose 
 import { MongooseModule } from '@nestjs/mongoose';
import { UploadModule } from './upload/upload.module';
 @Module({
   // 用 forRoot 方法连接数据库AddressBook
  imports: [UserModule, MongooseModule.forRoot(), UploadModule],


   controllers: [AppController],
   providers: [AppService],
 })
 export class AppModule {}
 

nest g res user 快速生成一个模块

实体类文件夹entities是后来自己建的,注意,我们所有有和数据库有关的操作,包括新增文档的字段,都必须要在此显示的声明

point.entity.ts


// 实体类得分表
 import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
 // @Prop 装饰器接受一个可选的参数,通过这个,你可以指示这个属性是否是必须的,是否需要默认值,或者是标记它作为一个常量,下面是例子

 import { Document } from 'mongoose';

type Eegres={
    mood:string
    presure:string
    relax:string
    concentrate:string
    tired:string
}


//  每个Schema对应MongoDB中的一个collection。
 @Schema()
//  描述集合的字段
 export class Point extends Document {
   
//    name: string;
   // 设置值为必填
//    @Prop({ required: true })
//    age: number;
  
//    height: number;
  
   @Prop()
   gaintestPoint:string
   @Prop()
   looktestPoint:string[]
   @Prop()
   viocetsetPoint:string
   @Prop()
   eegResult:string[]

   @Prop()
   totalityTestPoint:string
   @Prop()
   gameReview?:string
   @Prop({required:true,ref:'User'})
   personID:string
   @Prop()
   Addvice?:string
   @Prop()
   gaintestMp4?:string
 }
 export type PointDocument = Point & Document;
  // SchemaFactory 是 mongoose 内置的一个方法做用是读取模式文档 并创建 Schema 对象
 export const PointSchema = SchemaFactory.createForClass(Point);

/**
 * @name 
 * 原始 Schema 定义也可以被传递给装饰器。这也非常有用,举个例子,一个属性体现为一个嵌套对象而不是一个定义的类。要使用这个,需要从像下面一样从 @nestjs/mongoose 包导入 raw()
 * @Prop(raw({
         firstName: { type: String },
         lastName: { type: String }
        }))
   details: Record<string, any>;

 *  https://docs.nestjs.cn/9/techniques?id=mongo
 */


ref:'User'是关联User这个集合,后面会讲

user.entity.ts

// export class User {}


 /* user.schema.ts 数据库字段映射,相当于实体类*/
 import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
 // @Prop 装饰器接受一个可选的参数,通过这个,你可以指示这个属性是否是必须的,是否需要默认值,或者是标记它作为一个常量,下面是例子

 import { Document } from 'mongoose';

//  每个Schema对应MongoDB中的一个collection。
 @Schema()
//  描述集合的字段
 export class User extends Document {
   
//    name: string;
   // 设置值为必填
//    @Prop({ required: true })
//    age: number;
  
//    height: number;
   @Prop()
   age:string
   @Prop()
   identifier:string
   @Prop()
   name:string
   @Prop()
   nation:string
   @Prop()
   grade:string
   @Prop()
   schemeNum:string
   @Prop()
   organ:string
   @Prop()  
   sex:number
 }
 export type UserDocument = User & Document;
  // SchemaFactory 是 mongoose 内置的一个方法做用是读取模式文档 并创建 Schema 对象
 export const UserSchema = SchemaFactory.createForClass(User);


以下是一个crud模板

user.controller.ts

/* user.controller.ts */
// 引入 Nest.js 内置的各个功能
import { Body, Controller, Delete, Get, Param, Post, Put, Query } from '@nestjs/common';
// 引入用户服务
import { UserService } from './user.service';
// 引入创建用户 DTO 用于限制从接口处传来的参数
import { CreatePointDto,createPerson } from './dto/create-user.dto';

// 配置局部路由
@Controller('user')
export class UserController {
  constructor(private readonly userService: UserService) { }


  @Get('getpoints')
  async getPoints(@Query() query){
 
    
    return  await this.userService.getPoint(query.sid)
       
  }
 // 创建得分表
 @Post('createpoint')
 async createPoint(@Body() body: CreatePointDto) {
   return this.userService.create(body);
 }

// // 创建得分表
//   @Post('createUser')
//   async createUser(@Body() body: CreatePointDto) {
//     return this.userService.create(body);
//   }

// 添加用户
@Post('addUsers')
async addUsers(@Body() body:createPerson){
    return this.userService.addPerson(body)
}

// 根据名字查找用户
@Get('findUserName')
async findUserName(@Query ( ) query:{name:string}){

  
    return this.userService.findname(query.name)
}

  //查找所有 user 路由
  @Get('findAll')
  async findAll() {
    console.log('查找所有 user ');
    console.log(this.userService.findAll);

    return this.userService.findAll();
  }
  // 查找某一个用户路由
  @Get('findOne')
  async findOne(@Query() query: any) {
    // 从前端传来的参数中解出personID
    console.log(query.personID);
    
    return await this.userService.findOne(query.personID);
  }
  // 删除一个用户的路由
  @Delete(':sid')
  deleteUser(@Param() param: any) {
    console.log('dsdsdsd');

    return this.userService.delete(param.sid);
  }
  // 更改用户信息的路由
  @Put(':sid')
  updateUser(@Body() body: any, @Param() param: any) {
    return this.userService.updateUser(param.sid, body);
  }
}

 user.module.ts

  /* user.module.ts */
  import { MiddlewareConsumer, Module ,NestModule, RequestMethod } from '@nestjs/common';
  import { UserController } from './user.controller';
  import { UserService } from './user.service';
  import { MongooseModule } from '@nestjs/mongoose';
  import { UserSchema ,User} from './entities/user.entity';
import {Point,PointSchema } from './entities/point.entity'

  import {LoggerMiddleware} from "src/logger/logger.middleware"
  @Module({
     // MongooseModule提供了forFeature()方法来配置模块,即用来关联数据库实体类,包括定义哪些模型应该注册在当前范围中。
     // 如果你还想在另外的模块中使用这个模型,将MongooseModule添加到CatsModule的exports部分并在其他模块中导入CatsModule。
     // 这里的 name:'Users' 为集合名称,与 service 中注入的表名称对应两者不一样会报错
    imports: [MongooseModule.forFeature([
      { name: User.name, schema: UserSchema, collection: 'Users' },
      { name: Point.name, schema: PointSchema, collection: 'point' }
  ]),

  ],
    controllers: [UserController],
    providers: [UserService],
  })

  // 不知道怎么实现就查询它的类型
  export class UserModule  implements NestModule  {
    // 接收一个消费者,调用apply方法来注册这个中间件并指定要作用的路由
    configure(consumer: MiddlewareConsumer) {
      // 三种写法,局部注册中间件
      // consumer.apply(LoggerMiddleware).forRoutes('user')
      // consumer.apply(LoggerMiddleware).forRoutes({path:'user',method:RequestMethod.GET})
      consumer.apply(LoggerMiddleware).forRoutes(UserController)

    }
  }


user.service.ts

import { Model } from 'mongoose';
import { InjectModel } from '@nestjs/mongoose';
// import { User, UserDocument } from 'src/blog/schemas/blog.schemas';
import { User, UserDocument } from 'src/user/entities/user.entity';
import { Point, PointDocument } from './entities/point.entity'

import { CreatePointDto,createPerson } from './dto/create-user.dto';
import { Injectable } from '@nestjs/common';
import { lookupService } from 'dns';
@Injectable()
export class UserService {
  // 注册Schema后,可以使用 @InjectModel() 装饰器将 User 模型注入到 UserService 中:
  // 这里的'Users'需要和user.module定义的数据库表名对上
  constructor(
    @InjectModel(User.name) private userTest: Model<UserDocument>,
    @InjectModel(Point.name) private pointTest: Model<Point>
  ) { }

  // 查找全部的得分表1
  async getPoint(parmas): Promise<any> {
    if (!!parmas === false) {
      // 查询全部 根据参数判断1
      return await this.pointTest.find({}).populate('personID').exec()
    }
    else {
      return await this.pointTest.find({ personID: parmas }).populate('personID').exec()
    }
  }

  // 查找得分表
  async getPointonly(personID: string): Promise<any> {
    const temp = await this.pointTest.find({ _id: personID }).populate('personID').exec();

    
    return temp;
  }

  // 添加得分表
  async create(createUserDto: CreatePointDto): Promise<Point> {
    console.log(createUserDto);

    const createUser = new this.pointTest(createUserDto);
    const temp = await createUser.save();
    return temp;
  }

  //添加用户
  async addPerson(createPerson:createPerson){
    console.log(createPerson);

    const createUser = new this.userTest(createPerson);
    const temp = await createUser.save();
    return temp;
  }

  // 通过名字查找用户
async findname(name:string){
  console.log(name);
  
      const data = await this.userTest.find({
        name:name

      })
    return data
}

  // 查找所有用户
  async findAll(): Promise<User[]> {
    // 这里是异步的
    const temp = await this.userTest.find().exec();
    console.log(__dirname);
    return temp;
  }

  // 查找
  async findOne(personID: string): Promise<User[]> {
    // 这里是异步的
    // console.log(personID);

    const temp = await this.userTest.find({ _id: personID },).exec();
    return temp;
  }
  // 删除
  async delete(sid: number) {
    // 这里是异步的  remove 方法删除成功并返回相应的个数
    const temp = await this.userTest.deleteOne({ _id: sid });
    return temp;
  }
  // 修改
  async updateUser(sid: string, data: any) {
    // 这里是异步的  
    const temp = await this.userTest.updateOne({ _id: sid }, { $set: data });
    return temp;
  }
}

 这里有个问题

 这里会明确这两个变量的类型,

类型分别为

 ts 中类也可以作为接口被传入泛型,与interface的功能一致,这里其实我是学习网上的写法,网上的写法是Model<UserDocument>我的写法则是Model<User>

就类型来说Point与PointDocument应该是等价的

事实上ide推导的类型两者完全一致

猜你喜欢

转载自blog.csdn.net/apple_52957499/article/details/128642621