接上一篇
posts.controller.ts
findByIdAndUpdate、find、create、findByIdAndDelete都是mongoose的方法,与nest.js无关
import { Body, Controller, Delete, Get, Param, Post, Put, Query } from '@nestjs/common';
import { ApiOperation, ApiProperty, ApiTags } from '@nestjs/swagger';
import { PostModel } from './posts.model';
// 标识创建帖子的参数详情
class createPostDto{
@ApiProperty({description:'帖子标题'})
title:string
@ApiProperty({description:'帖子内容'})
content:string
}
@Controller('posts')
@ApiTags('帖子')
export class PostsController {
@Get()
@ApiOperation({summary:'显示帖子列表'})
async index() {
//查找帖子
return await PostModel.find()
}
@Post()
@ApiOperation({summary:"创建帖子"})
// 获取post请求的数据用@Body()装饰器获取数据,get用@query()
async create(@Body() Body:createPostDto){
//创建帖子
await PostModel.create(Body)
return{
success:true
}
}
@Get(':id')
@ApiOperation({summary:"帖子详情"})
async detail(@Param('id') id:string){
//根据id查帖子
return await PostModel.findById(id)
}
@Put(':id')
@ApiOperation({summary:'编辑帖子详情'})
async update(@Param('id') id:string,@Body() body:createPostDto){
//根据id修改帖子
await PostModel.findByIdAndUpdate(id,body)
return {
success:true
}
}
@Delete(':id')
@ApiOperation({summary:'删除帖子'})
async remove(@Param('id') id:string){
//根据id删除帖子
await PostModel.findByIdAndDelete(id)
return{
success:true
}
}
}