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

相关推荐
李白的天不白8 小时前
webpack 与 webpack-cli 版本匹配问题
前端·webpack·node.js
前端之虎陈随易11 小时前
2年没用Nodejs了,Bun很香
linux·前端·javascript·vue.js·typescript
Yue16811 小时前
啥子都能看懂的TypeScript快速入门
typescript
李白的天不白14 小时前
webpack 与axios 版本冲突问题
前端·webpack·node.js
donecoding16 小时前
pnpm 全局包与 nvm 的真相:命令永在,运行时随缘
node.js·claude
老蒋每日coding17 小时前
Node.js 安装指南(Mac 版本)
macos·node.js
吴声子夜歌1 天前
Node.js——JSON-Server轻量级RESTful API
node.js·json·restful·json-server
爬山算法1 天前
MongoDB(118)如何在升级过程中进行数据备份?
数据库·mongodb·oracle
We་ct1 天前
LeetCode 72. 编辑距离:动态规划经典题解
前端·算法·leetcode·typescript·动态规划