Nestjs 使用mongodb
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的更多相关文章
- Nestjs mongodb
nestjs 文档 mongoose 文档 使用"@meanie/mongoose-to-json"转换查询后返回的json数据 将"_id"转为"i ...
- Nestjs 缓存
Docs: https://docs.nestjs.com/techniques/caching yarn add @nestjs/mongoose mongoose yarn add cache-m ...
- 在 Nest.js 中使用 MongoDB 与 TypeORM
在 Nest.js 中使用 MongoDB 与 TypeORM 首先要在 database 文件夹里建立DatabaseModule模块文件, // database/database.module. ...
- Nestjs入门学习教程
初次接触Nest,有问题欢迎指出: 简介 NestJS是一个用于构建高效.可扩展的Node.js服务器端应用程序的开发框架.简单来说是一款Node.js的后端框架. 它利用JavaScript的渐进增 ...
- 【翻译】MongoDB指南/聚合——聚合管道
[原文地址]https://docs.mongodb.com/manual/ 聚合 聚合操作处理数据记录并返回计算后的结果.聚合操作将多个文档分组,并能对已分组的数据执行一系列操作而返回单一结果.Mo ...
- 【翻译】MongoDB指南/CRUD操作(四)
[原文地址]https://docs.mongodb.com/manual/ CRUD操作(四) 1 查询方案(Query Plans) MongoDB 查询优化程序处理查询并且针对给定可利用的索引选 ...
- 【翻译】MongoDB指南/CRUD操作(三)
[原文地址]https://docs.mongodb.com/manual/ CRUD操作(三) 主要内容: 原子性和事务(Atomicity and Transactions),读隔离.一致性和新近 ...
- 【翻译】MongoDB指南/CRUD操作(二)
[原文地址]https://docs.mongodb.com/manual/ MongoDB CRUD操作(二) 主要内容: 更新文档,删除文档,批量写操作,SQL与MongoDB映射图,读隔离(读关 ...
- 【翻译】MongoDB指南/CRUD操作(一)
[原文地址]https://docs.mongodb.com/manual/ MongoDB CRUD操作(一) 主要内容:CRUD操作简介,插入文档,查询文档. CRUD操作包括创建.读取.更新和删 ...
随机推荐
- ubuntu下使用crontab
创建crontab任务 参考:https://www.cnblogs.com/Icanflyssj/p/5138851.html 3. crontab常用的几个命令格式 crontab -l //显示 ...
- vue-cli配置多入口多出口,实现一个项目两个访问地址,区分不同上线环境
最近工作中需要把项目分割成两块,一块需要跑在微信中,通过微信jdk获取用户资料默认登录,一部分需要给原生app做webview的内嵌页面,当然这部分内容是不跑在微信中的. 所以我想到了把项目分成两部分 ...
- AxWindowsMediaPlayer控件的使用
首先要知道如何将控件添加到工具箱中,步骤如下: “工具箱”中单击右键,选择“选择项”菜单,打开“选择工具箱项”窗口,选择“COM组件”标签,在列表中找到并勾选“Windows Media Player ...
- (三)underscore.js框架Objects类API学习
keys_.keys(object) Retrieve all the names of the object's properties. _.keys({one: 1, two: 2, three ...
- [Linux] - Windows与Linux网络共享文件夹挂载方法
Windows与Linux网络SMB方式文件夹共享挂载 本示例系统: Windows 2003+ Linux-Centos/Ubuntu 本示例全为命令行操作,如何使用Windows.Linux命令行 ...
- PowerShell 显示气球提示框 2
https://www.itninja.com/blog/view/reboot-required-toast-notifications-for-windows-machines [void][Sy ...
- CentOS5.9 编译Emacs 24
从Emacs官方网站下载最新版解压后,执行 ./configure 得到错误信息: configure: error: The following required libraries were no ...
- zookeeper做集群后启动不了,大部分原因是防火墙未关闭
zookeeper做单机版,可以正常启动:但是zookeeper做集群后启动不了,大部分原因是防火墙未关闭. centos的关闭防火墙方法比较独立. systemctl stop firewalld. ...
- Linux常用指令笔记
目标:统计当前目录下java文件的个数 指令:`ls -R ./ | grep .java$ | wc -l` 原理:`ls -R ./`列出当前文件夹下的所有FILE,包括目录以及文件;`grep ...
- 当 return 遇到 try
. . . . . 今天有同事和我探讨在群里看到的一道有趣的题目,在探讨的过程中让我搞清楚了一些曾经模糊的概念,特此记录下来. 题目给出如下代码,问运行后打印的结果是什么. public static ...