zoukankan      html  css  js  c++  java
  • [NestJS] Basic CRUD with Mongoose & NestJS

    main.ts

    import { NestFactory } from '@nestjs/core';
    
    import { AppModule } from './app.module';
    
    async function bootstrap() {
      const app = await NestFactory.create(AppModule);
    
      app.setGlobalPrefix('api');
    
      await app.listen(9000);
    }
    
    bootstrap();

    Module:

    import { Module } from '@nestjs/common';
    import { MongooseModule } from '@nestjs/mongoose';
    import { CoursesController } from './controllers/courses.controller';
    import { CoursesSchema } from './schemas/courses.schema';
    import { CoursesRepository } from './repositories/courses.repository';
    
    @Module({
      imports: [
        MongooseModule.forFeature([
          {
            name: 'Course',
            schema: CoursesSchema,
          },
        ]),
      ],
      controllers: [CoursesController],
      providers: [CoursesRepository],
    })
    export class CoursesModule {}

    Schema:

    import * as mongoose from 'mongoose';
    
    export const CoursesSchema = new mongoose.Schema({
      seqNo: Number,
      url: String,
      iconUrl: String,
      courseListIcon: String,
      description: String,
      longDescription: String,
      category: String,
      lessonsCount: Number,
      promo: Boolean,
    });

    Controller:

    import {
      Controller,
      Get,
      Param,
      Put,
      Body,
      Delete,
      Post,
    } from '@nestjs/common';
    import { Course } from '../../../../shared/course';
    import { CoursesRepository } from '../repositories/courses.repository';
    
    @Controller('courses')
    export class CoursesController {
      constructor(private couresDB: CoursesRepository) {}
    
      @Post()
      async createCourse(@Body() course: Partial<Course>): Promise<Course> {
        return this.couresDB.addCourse(course);
      }
    
      @Get()
      async findAllCourses(): Promise<Course[]> {
        return this.couresDB.findAll();
      }
    
      @Put(':courseId')
      async updateCourse(
        @Param('courseId') courseId: string,
        @Body() changes: Partial<Course>,
      ): Promise<Course> {
        return this.couresDB.updateCourse(courseId, changes);
      }
    
      @Delete(':courseId')
      async deleteCourse(@Param('courseId') courseId: string) {
        return this.couresDB.deleteCourse(courseId);
      }
    }

    Repository:

    import { Injectable } from '@nestjs/common';
    import { Course } from '../../../../shared/course';
    import { InjectModel } from '@nestjs/mongoose';
    import { Model } from 'mongoose';
    
    @Injectable()
    export class CoursesRepository {
      constructor(@InjectModel('Course') private courseModel: Model<Course>) {}
    
      async addCourse(course: Partial<Course>): Promise<Course> {
        // Create a memory version
        const newCourse = this.courseModel(course);
        // save to db
        await newCourse.save();
        // return the FE version data
        return newCourse.toObject({
          version: false, // without any mongoose props
        });
      }
    
      async findAll(): Promise<Course[]> {
        return this.courseModel.find();
      }
    
      async updateCourse(id: string, changes: Partial<Course>): Promise<Course> {
        return this.courseModel.findOneAndUpdate(
          { _id: id },
          changes,
          { new: true }, // return a new version of the data
        );
      }
    
      async deleteCourse(id: string) {
        return this.courseModel.deleteOne({ _id: id });
      }
    }
  • 相关阅读:
    MySQL的char和varchar针对空格的处理
    单KEY业务,数据库水平切分架构实践
    接口测试学习笔记1-接口测试的用例设计
    Robot Framework源码解析(2)
    Robot Framework 源码解析(1)
    Python学习笔记1 -- TypeError: 'str' object is not callable
    OKHttp源码学习同步请求和异步请求(二)
    OKHttp源码学习--HttpURLConnection HttpClient OKHttp Get and post Demo用法对比
    Javapoet源码解析
    Universal-Image-Loader源码解解析---display过程 + 获取bitmap过程
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12184475.html
Copyright © 2011-2022 走看看