nestjs-mongodb-demo

原创
2019/10/14 16:13
阅读数 63

Docs: https://docs.nestjs.com/techniques/mongodb

yarn add @nestjs/mongoose mongoose

链接

// sec/app.module.ts

import { Module }from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';

import { MongooseModule } from '@nestjs/mongoose'
import { CatsModule } from './cats/cats.module';

@Module({
  imports: [
    MongooseModule.forRoot('mongodb://localhost/ajanuw', { useNewUrlParser: true }), // ajanuw数据库的名字
    CatsModule
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

模型注入

// src/cats/schemas/cat.schema.ts

import * as mongoose from 'mongoose';

export const CatSchema = new mongoose.Schema({
  name: String,
});

cats.module.ts 中使用

import { Module } from '@nestjs/common';
import { CatsController } from './cats.controller';
import { CatsService } from './cats.service';
import { MongooseModule } from '@nestjs/mongoose'
import { CatSchema } from './schemas/cat.schema'

@Module({
  imports: [
    MongooseModule.forFeature([ // Schema 定义数据库的结构
      { name: 'Cat', schema: CatSchema } // name: 'Cat'  cats 表, Cat 必须和service时@InjectModel('Cat')的一样
    ])
  ],
  controllers: [CatsController],
  providers: [CatsService]
})
export class CatsModule {}

cats.service.ts 中注入 CatModel

import { Injectable } from '@nestjs/common';
import { Model } from 'mongoose'
import { InjectModel } from '@nestjs/mongoose'

import { Cat } from './interfaces/cat.interface'
import { CreateCat } from './class/create-cat.class'

const l = console.log
@Injectable()
export class CatsService {
  constructor(
    @InjectModel('Cat') private readonly catModel: Model<Cat>  // Model 可以操作数据表
  ){}

  async create(cat: CreateCat): Promise<Cat> {
    const createdCat = new this.catModel(cat)
    l(createdCat) // { _id: 5b8e2faba163251c9c769e6e, name: '小黑猫' }  返回一个docment
    return await createdCat.save()  // 保存 document
    //  return this.catModel.insertMany(cat)
  }

  async findAll(): Promise<Cat[]> {
    return await this.catModel.find().exec()
  }
}

cats.controller.ts

import { Controller, Get, Post, Body } from '@nestjs/common';
import { CatsService } from './cats.service'
import { CreateCat } from './class/create-cat.class'

const l = console.log;
@Controller('cats')
export class CatsController {

  constructor(
    private readonly catsServer: CatsService
  ){}

  @Post()
  create(@Body() cat: CreateCat){
     this.catsServer.create(cat);
  }

  @Get()
  findAll(){
    return this.catsServer.findAll()
  }
}

CreateCat

export class CreateCat {
  readonly name: string;
}

Cat

import { Document } from 'mongoose'

export interface Cat extends Document {
  readonly name: string;
}

完整的 cats.controller.ts

import { Controller, Get, Post, Body, Query, Delete } from '@nestjs/common';
import { CatsService } from './cats.service'
import { CreateCat } from './class/create-cat.class'

const l = console.log;
@Controller('cats')
export class CatsController {
  constructor(
    private readonly catsServer: CatsService
  ){}
  @Post()
  create(@Body() cat: CreateCat){
     this.catsServer.create(cat);
  }

  @Get()
  findAll(){
    return this.catsServer.findAll()
  }

  @Get('find-cat')
  findCat(@Query('catName') catName){
    return this.catsServer.findCat(catName)
  }

  @Post('update-cat-name')
  updateCatName(@Body() body){
    this.catsServer.updateCatName(body)
  }

  @Delete('remove-cat')
  removeCat(@Body('catName') catName){
    this.catsServer.removeCat(catName)
  }
}

cats.service.ts

import {
  Injectable,
  HttpException,
  HttpStatus
} from '@nestjs/common';
import {
  Model
} from 'mongoose'
import {
  InjectModel
} from '@nestjs/mongoose'
import {
  Cat
} from './interfaces/cat.interface'
import {
  CreateCat
} from './class/create-cat.class'

const l = console.log;
@Injectable()
export class CatsService {
  constructor(
    @InjectModel('Cat') private readonly catModel: Model < Cat >
  ) {}

  async create(cat: CreateCat): Promise < Cat > {
    // const createdCat = new this.catModel(cat)
    // return await createdCat.save()
    return this.catModel.insertMany(cat)
  }

  async findAll(): Promise < Cat[] > {
    return await this.catModel.find().exec()
  }

  async findCat(name: string): Promise < Cat[] > {
    if (!name) {
      throw new HttpException('请求参数不正确.', HttpStatus.FORBIDDEN)
    }
    let resCat = this.catModel.find({
      name
    })
    return resCat
  }

  async updateCatName({name, newName}) {
    if(!name || !newName){
      throw new HttpException('请求参数不正确.', HttpStatus.FORBIDDEN)
    }

     const where = {
        name: name
    };
    const update = {
        $set: {
            name: newName
        }
    };
    return await this.catModel.updateOne(where, update);   
  }

  async removeCat(catName){
    l(catName)
    if(!catName){
      throw new HttpException('请求参数不正确.', HttpStatus.FORBIDDEN)
    }
    return await this.catModel.deleteOne({name: catName})
  }
}
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部