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

Nestjs 使用mongodb的更多相关文章

  1. Nestjs mongodb

    nestjs 文档 mongoose 文档 使用"@meanie/mongoose-to-json"转换查询后返回的json数据 将"_id"转为"i ...

  2. Nestjs 缓存

    Docs: https://docs.nestjs.com/techniques/caching yarn add @nestjs/mongoose mongoose yarn add cache-m ...

  3. 在 Nest.js 中使用 MongoDB 与 TypeORM

    在 Nest.js 中使用 MongoDB 与 TypeORM 首先要在 database 文件夹里建立DatabaseModule模块文件, // database/database.module. ...

  4. Nestjs入门学习教程

    初次接触Nest,有问题欢迎指出: 简介 NestJS是一个用于构建高效.可扩展的Node.js服务器端应用程序的开发框架.简单来说是一款Node.js的后端框架. 它利用JavaScript的渐进增 ...

  5. 【翻译】MongoDB指南/聚合——聚合管道

    [原文地址]https://docs.mongodb.com/manual/ 聚合 聚合操作处理数据记录并返回计算后的结果.聚合操作将多个文档分组,并能对已分组的数据执行一系列操作而返回单一结果.Mo ...

  6. 【翻译】MongoDB指南/CRUD操作(四)

    [原文地址]https://docs.mongodb.com/manual/ CRUD操作(四) 1 查询方案(Query Plans) MongoDB 查询优化程序处理查询并且针对给定可利用的索引选 ...

  7. 【翻译】MongoDB指南/CRUD操作(三)

    [原文地址]https://docs.mongodb.com/manual/ CRUD操作(三) 主要内容: 原子性和事务(Atomicity and Transactions),读隔离.一致性和新近 ...

  8. 【翻译】MongoDB指南/CRUD操作(二)

    [原文地址]https://docs.mongodb.com/manual/ MongoDB CRUD操作(二) 主要内容: 更新文档,删除文档,批量写操作,SQL与MongoDB映射图,读隔离(读关 ...

  9. 【翻译】MongoDB指南/CRUD操作(一)

    [原文地址]https://docs.mongodb.com/manual/ MongoDB CRUD操作(一) 主要内容:CRUD操作简介,插入文档,查询文档. CRUD操作包括创建.读取.更新和删 ...

随机推荐

  1. oracle操作字符串:拼接、替换、截取、查找、长度、判断

    1.拼接字符串 1)可以使用“||”来拼接字符串 select '拼接'||'字符串' as str from dual 2)通过concat()函数实现 select concat('拼接', '字 ...

  2. Node.js文件编码格式的转换

    项目很多 lua 文件不是 utf-8格式,使用 EditPlus 查看的时候,显示为ASCII.还有的是带BOM的,带BOM倒好处理,之前写过,有一定规律. ASCII编码就比较蛋疼,通过搜索网上资 ...

  3. 【Kibana】自定义contextPath

    #https://www.elastic.co/guide/en/kibana/5.0/_configuring_kibana_on_docker.html#https://discuss.elast ...

  4. 未能加载文件或程序集“SuperMap.Data.dll”

    重新配置的新的开发环境,使用的是原来的工程文件,编译通过,运行报错:"未能加载文件或程序集"SuperMap.Data.dll"或它的某一个依赖项.找不到指定的模块&qu ...

  5. Java代码质量监控工具Sonar安装

    1.  代码质量七宗罪 Sonar是一个代码质量管理系统.它的帮助文档开篇明义,提出了代码质量的七宗罪.总结的比較到位.最好还是一看: 1.        Bug和隐藏Bug(Bugs and Pot ...

  6. lsof详解

    from:https://www.cnblogs.com/the-study-of-linux/p/5501593.html lsof (list open files)是一个列出当前系统打开文件的工 ...

  7. 【PHP】解析PHP中的数组

    目录结构: contents structure [-] 创建数组 删除数组 栈结构 常用的数组处理函数 在这篇文章中,笔者将会介绍PHP中数组的使用,以及一些注意事项.之前笔者已经说过PHP是一门弱 ...

  8. adb shell am broadcast 手动发送广播及adb shell am/pm其他命令

    版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/zi_zhe/article/details/72229201 在命令行可用adb shell am ...

  9. Xshell设置密钥登录CentOS6.5_64位(文字命令版)

    1.新建/root/.ssh目录 mkdir /root/.ssh 2.创建authorized_keys文件 vi /root/.ssh/authorized_keys 3.复制公钥内容保存 :wq ...

  10. 减少网站跳转时间,增强网站数据安全——HSTS 详解

    近年来随着 Google.Apple.百度等公司不断推动 HTTPS 普及,全网 HTTPS 已是大势所趋.目前多数网站都已经支持 HTTPS 访问,但是在由 HTTP 转向 HTTPS 路程中,不少 ...