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.输出结果

相关推荐
不会敲代码18 小时前
Zustand:轻量级状态管理,从入门到实践
前端·typescript
不会敲代码116 小时前
从零开始用 TypeScript + React 打造类型安全的 Todo 应用
前端·react.js·typescript
helloweilei17 小时前
javascript 结构化克隆
javascript·node.js
小蜜蜂dry1 天前
nestjs学习 - 控制器、提供者、模块
前端·node.js·nestjs
San301 天前
手写 Mini Cursor:基于 Node.js 与 LangChain 的开发实战
langchain·node.js·agent
赵小胖胖1 天前
解决方案与原理解析:TypeScript 中 Object.keys() 返回 string[] 导致的索引类型丢失与优雅推导方案
typescript
前端付豪2 天前
Nest 项目小实践之图书增删改查
前端·node.js·nestjs
sunny_2 天前
面试踩大坑!同一段 Node.js 代码,CJS 和 ESM 的执行顺序居然是反的?!99% 的人都答错了
前端·面试·node.js
minge3 天前
借助 Trae Builder 把 TypeScript 的碎片化学习记录整理成文档
typescript