一、实现 Article 集合的增删改查
1、创建接口 article.interface.ts
nest g interface interface/article
export interface Article {
_id?: String;
name?: String;
author?: String;
keywords?: String;
content?: String;
status?: Number;
}
2、使用接口 article.service.ts
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Article } from 'src/interface/article.interface';
@Injectable()
export class ArticleService {
// 使用 InjectModel 获取 admin.module.ts 中的 MongooseModule 的参数
constructor(@InjectModel('Article') private articleModel) { }
// 根据条件查询文章
async findAll(json: Article = {}, fields?: String) {
var result = await this.articleModel.find(json, fields).exec();
return result;
}
// 增加数据
async add(json: Article) {
var article = new this.articleModel(json);
var result = await article.save();
return result;
}
// 修改数据
async update(json1: Article, json2: Article) {
var result = await this.articleModel.updateOne(json1, json2);
return result;
}
// 删除数据
async delete(json: Article) {
var result = await this.articleModel.deleteOne(json);
return result;
}
}
3、操作数据 article.controller.ts
import { ArticleService } from './../../service/article/article.service'; // 引入服务
import { Controller, Get } from '@nestjs/common';
@Controller('admin/article')
export class ArticleController {
constructor(private articleService: ArticleService) { } // 依赖注入
@Get()
async index() {
// name author 是查询返回的字段
var result = await this.articleService.findAll({ "_id": "618b4e06539e79bf2feb4ae4" }, 'name author');
return result;
}
@Get('indexAll')
async indexAll() {
var result = await this.articleService.findAll();
return result;
}
@Get('add')
async doAdd() {
var result = await this.articleService.add({
title: "大地专栏123123",
author: "大地专栏123123",
status: 1
})
return result;
}
@Get('update')
async doUpdate() {
var result = await this.articleService.update({ _id: "618b8160c6584bf0269f92d4" }, {
title: "大地专栏",
author: "大地专栏123123"
})
return result;
}
@Get('delete')
async doDelete() {
var result = await this.articleService.delete({ _id: "618b8160c6584bf0269f92d4" })
return result;
}
}