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

相关推荐
wordbaby1 小时前
🎯 satisfies 关键字详解(TypeScript)
前端·typescript
超级土豆粉1 小时前
从0到1写一个适用于Node.js的User Agent生成库
linux·ubuntu·node.js
空中湖4 小时前
‘pnpm‘ 不是内部或外部命令,也不是可运行的程序
npm·node.js
SailingCoder5 小时前
grafana-mcp-analyzer:基于 MCP 的轻量 AI 分析监控图表的运维神器!
运维·人工智能·typescript·node.js·grafana
又又呢8 小时前
前端面试题总结——webpack篇
前端·webpack·node.js
avoidaily15 小时前
使用Node.js分片上传大文件到阿里云OSS
阿里云·node.js·云计算
xd0000215 小时前
8.axios Http网络请求库(1)
node.js
孟孟~16 小时前
npm run dev 报错:Error: error:0308010C:digital envelope routines::unsupported
前端·npm·node.js
孟孟~16 小时前
npm install 报错:npm error: ...node_modules\deasync npm error command failed
前端·npm·node.js
狂炫一碗大米饭16 小时前
一文打通TypeScript 泛型
前端·javascript·typescript