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. git忽略已加入到版本库的文件

    项目中,我们会用到 '.gitignore' 来忽略一些文件,不记录这些文件的版本控制. 然而,经常发现,已经添加到了 '.gitignore' 的文件/目录,每次的修改等扔会记录版本. 产生这种原因 ...

  2. 20、MySQLdb

    MySQLdb win64位安装python-mysqldb1.2.5 ubuntu下安装MySQLdb sudo apt-get install python-MySQLdb 导入MySQLdb库 ...

  3. bootstrap3-iframe-modal子页面在父页面显示模态框

    本文灵感来自:http://www.cnblogs.com/chengxuyuanzhilu/p/5132328.html 子页面内容 //打开模态框 function openMySelectMod ...

  4. Redis接口的调用

    1.hiredis是redis数据库的C接口,目录为/redis-3.2.6/deps/hiredis 2.示例代码如下: #include <stdio.h> #include < ...

  5. tmunx error:invalid option: status-utf8 invalid option: utf8

    修改为:set-window-option -gq mouse off set-window-option -gq mode-mouse off set-option -gq status-utf8 ...

  6. Couldn't find log associated with operation handle: OperationHandle [opType=EXECUTE_STATEMENT, getHandleIdentifier ()=5687ff62-aa71-4b47-af6c-89f6a3f7a1fe]

    这个异常的出现是因为hive-site-xml中的hive.server2.logging.operation.log.location属性未配置正确: 修改为: <property> & ...

  7. 关于VC预定义常量_WIN32,WIN32,_WIN64

    VC2012 下写 Windows 程序时,有时需要判断编译环境.在之前的文章<判断程序是否运行在 Windows x64 系统下.>里说过如何在运行期间判断系统环境,但在编译时如何判断? ...

  8. OpenLayers WorkShop 快速学习通道

    学习地址:https://openlayers.org/workshop/en/ OpenLayers Workshop Introduction Basics Creating a map Zoom ...

  9. Jenkins自动部署增加http状态码校验

    公司推进Jenkins自动化部署,因为web站点都是集群部署,部署需要测试指定服务器web服务是否成功启动,页面是否正常访问,经过不断baidu发现,python的request模块可以很好的解决这一 ...

  10. Windows利用文件夹映射来同步文件

    在windows服务器上有时有这样的需求: 你的文件在f:\test中,但由于其它原因用户访问的是e:\test,如果又希望e:\test 中的文件与f:\test的保持同步,除了用同步软件来做外,可 ...