nest使用mongoose

1.安装依赖包

TypeScript 复制代码
npm install --save @typegoose/typegoose 

npm install --save mongoose 

2.在man.ts中引入

TypeScript 复制代码
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as mongoose from 'mongoose';
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
                                                        //dbName数据库名称
  await mongoose.connect('mongodb://localhost:27017/', { dbName: 'reactDataBase' })
    .then(() => console.log('连接成功')).catch(err => console.log(err));
  await app.listen(3000);
}
bootstrap();

3.定义模型

新建一个user.scheam.ts文件

TypeScript 复制代码
import { prop, getModelForClass } from '@typegoose/typegoose';
class User {

    @prop({ required: true })
    public username: {
        type: String,
        default: ""
    }
    @prop({ required: true })
    password: {
        type: String,
        default: ""
    }
    @prop()
    avatar: {
        type: String,
        default: ""
    }
    @prop()
    description: {
        type: String,
        default: ""
    }
    @prop()
    sex: {
        type: String,
        default: "male"
    }
}

export const UserModel = getModelForClass(User, {
    //为模型取名,默认为类的名字+s
    schemaOptions: { collection: 'users' },
})

4.在service中使用

TypeScript 复制代码
import { Injectable } from '@nestjs/common';
//导入模型
import { UserModel } from "../Schema/user.schema"
import * as mongoose from 'mongoose';
@Injectable()
export class UserService {
  async findOne(id) {
    const res = await UserModel.aggregate([
      {
        $match: { _id: new mongoose.Types.ObjectId(id) }

      }
    ])
    console.log(res)
    return res;
  }


}

5.在controller中调用

TypeScript 复制代码
import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
import { UserService } from './User.service';


@Controller('user')
export class UserController {
  constructor(private readonly UerService: UserService) { }

  @Get()
  findOne() {
    return this.UserService.findOne('661a45e5d371586eeb837e9a');
  }


}

6.输出结果

相关推荐
AI视觉网奇2 小时前
pnpm 安装笔记
node.js
奔跑的呱呱牛2 小时前
xlsx 已停止维护且存在漏洞!推荐一个可直接替代的 npm 库
前端·npm·node.js·xlsx·sheetjs
jump_jump7 小时前
用 3100 个数字造一台计算机
性能优化·架构·typescript
这是个栗子10 小时前
TypeScript(三)
前端·javascript·typescript·react
码云之上13 小时前
从一个截图函数到一个 npm 包——pdf-snapshot 的诞生记
前端·node.js·github
lpfasd12314 小时前
TypeScript + Cloudflare 全家桶部署项目全流程
前端·javascript·typescript
行者-全栈开发15 小时前
腾讯地图 Map Skills 快速入门:从零搭建 AI 智能行程规划应用
人工智能·typescript·腾讯地图·ai agent·mcp 协议·map skills·智能行程规划
Kel15 小时前
Pi Monorepo Stream Event Flow 深度分析
人工智能·架构·node.js
梁山好汉(Ls_man)15 小时前
鸿蒙_ArkTS解决Duplicate function implementation错误
开发语言·华为·typescript·harmonyos·鸿蒙
米丘16 小时前
Connect 深度解析:Node.js 中间件框架的基石
javascript·http·node.js