一、实现 Article 集合的增删改查

1、创建接口 article.interface.ts
  1. nest g interface interface/article
  2. export interface Article {
  3. _id?: String;
  4. name?: String;
  5. author?: String;
  6. keywords?: String;
  7. content?: String;
  8. status?: Number;
  9. }

2、使用接口 article.service.ts
  1. import { Injectable } from '@nestjs/common';
  2. import { InjectModel } from '@nestjs/mongoose';
  3. import { Article } from 'src/interface/article.interface';
  4. @Injectable()
  5. export class ArticleService {
  6. // 使用 InjectModel 获取 admin.module.ts 中的 MongooseModule 的参数
  7. constructor(@InjectModel('Article') private articleModel) { }
  8. // 根据条件查询文章
  9. async findAll(json: Article = {}, fields?: String) {
  10. var result = await this.articleModel.find(json, fields).exec();
  11. return result;
  12. }
  13. // 增加数据
  14. async add(json: Article) {
  15. var article = new this.articleModel(json);
  16. var result = await article.save();
  17. return result;
  18. }
  19. // 修改数据
  20. async update(json1: Article, json2: Article) {
  21. var result = await this.articleModel.updateOne(json1, json2);
  22. return result;
  23. }
  24. // 删除数据
  25. async delete(json: Article) {
  26. var result = await this.articleModel.deleteOne(json);
  27. return result;
  28. }
  29. }

3、操作数据 article.controller.ts
  1. import { ArticleService } from './../../service/article/article.service'; // 引入服务
  2. import { Controller, Get } from '@nestjs/common';
  3. @Controller('admin/article')
  4. export class ArticleController {
  5. constructor(private articleService: ArticleService) { } // 依赖注入
  6. @Get()
  7. async index() {
  8. // name author 是查询返回的字段
  9. var result = await this.articleService.findAll({ "_id": "618b4e06539e79bf2feb4ae4" }, 'name author');
  10. return result;
  11. }
  12. @Get('indexAll')
  13. async indexAll() {
  14. var result = await this.articleService.findAll();
  15. return result;
  16. }
  17. @Get('add')
  18. async doAdd() {
  19. var result = await this.articleService.add({
  20. title: "大地专栏123123",
  21. author: "大地专栏123123",
  22. status: 1
  23. })
  24. return result;
  25. }
  26. @Get('update')
  27. async doUpdate() {
  28. var result = await this.articleService.update({ _id: "618b8160c6584bf0269f92d4" }, {
  29. title: "大地专栏",
  30. author: "大地专栏123123"
  31. })
  32. return result;
  33. }
  34. @Get('delete')
  35. async doDelete() {
  36. var result = await this.articleService.delete({ _id: "618b8160c6584bf0269f92d4" })
  37. return result;
  38. }
  39. }