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 });
      }
    }
  • 相关阅读:
    Andorid之官方导航栏Toobar
    使用ECharts实现数据图表分析
    内存优化之封装九宫格
    xUtils框架的使用详解
    IOS 生成本地验证码
    android之官方导航栏ActionBar(三)之高仿优酷首页
    Android官方导航栏ActionBar(二)—— Action View、Action Provider、Navigation Tabs的详细用法
    IOS 实现界面本地化(国际化)
    Windows7 64位压缩包安装MySQL5.7.9
    Debian 8.2 下安装MySQL5.7.9 Generic Binaries
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12184475.html
Copyright © 2011-2022 走看看