【问题标题】:How to create nested DTO class in NestJS corresponding to Schema如何在 NestJS 中创建与 Schema 对应的嵌套 DTO 类
【发布时间】:2022-02-26 20:14:36
【问题描述】:

我是 NestJs 的新手,我想在 Mongoose 中创建嵌套模式,因为我想在我的数据库中使用这个数据结构:

{
  name:"John",
   age:28,
  address:{
     city:"Delhi",
     state:"Delhi
  }
} 

为此,我在猫鼬模式下创建了:

user.schema.ts

import mongoose from "mongoose";

export const UserSchema = new mongoose.Schema({

 name:{type:String},
 age:{type:Number},
 address:{
     city:{type:String},
     state:{type:String}
  }
});

如何为这个架构编写 Dto 类。有人告诉我我想在数据库中添加数据。

【问题讨论】:

    标签: mongodb nestjs


    【解决方案1】:

    您可以通过以下方式简单地创建两个 DTO 类。

    export class AdressDto {
        readonly city: string;
        readonly state: string;
    }
    export class UserDto {
        readonly name: string;
        readonly age: number;
        readonly address: AdressDto
    }
    

    在Nestjs官方documentation你可以找到如何使用DTO 在您的控制器中,如果您想使用它们,还可以找到如何使用validators

    【讨论】:

      猜你喜欢
      • 2021-08-23
      • 1970-01-01
      • 2020-09-03
      • 2014-01-10
      • 2021-11-07
      • 2019-04-27
      • 1970-01-01
      • 1970-01-01
      • 2021-04-22
      相关资源
      最近更新 更多