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 }); } }