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

相关推荐
螺丝钉tina2 小时前
[Playwright ][16]Playwright + TypeScript API 自动化测试实战:API测试
前端·javascript·typescript
ClouGence6 小时前
MongoDB 双向同步如何防止数据循环?(附实操指南)
数据库·mongodb
华玥作者7 小时前
Vue 3 + TypeScript + uni-app 组件库推荐:hy-app(华玥组件库)
vue.js·typescript·uni-app
wno7047 小时前
node.js中使用jquery
前端·node.js·jquery
damoluomu1 天前
Node 的 Headless 出厂没有前台,Java 的 Headless 是从门户里长出来的
java·开发语言·node.js
Momo__1 天前
你写的 import 重试,从来没生效过
前端·javascript·typescript
Dumbness1 天前
一个手机号验证码登录接口的五个坑:无限发码、无限试码,传个数字就让 Express 进程退出
node.js·express
怒放的生命19911 天前
本地用 pnpm 省磁盘,团队继续用 npm:极简实践
前端·npm·node.js
码农阿豪1 天前
MongoDB迁移到金仓数据库:商品属性继续灵活存,订单报表交给 SQL
数据库·sql·mongodb