【问题标题】:How to add nested array of objects with @Prop decorator from @nestjs/mongoose如何使用来自@nestjs/mongoose 的@Prop 装饰器添加嵌套的对象数组
【发布时间】:2022-01-15 01:38:27
【问题描述】:

当我在道具装饰器中使用嵌套的对象数组时:

@Schema()
export class Child {
  @Prop()
  name: string;
}
    
@Schema()
export class Parent {
  @Prop({type: [Child], _id: false}) // don't need `_id` for nested objects
  children: Child[];
}

export const ParentSchema = SchemaFactory.createForClass(Parent);

我收到一个错误:

TypeError: Invalid schema configuration: `Child` is not a valid type within the array `children`.

如果我需要使用@Prop({_id: false})(以保持嵌套架构独立),我该如何解决这个问题?


如果我们将道具装饰器更改为@Prop([Child]),它可以工作,但是我们需要为嵌套对象禁用_id

@Schema({_id: false})
export class Child {
  @Prop()
  name: string;
}

@Schema()
export class Parent {
  @Prop([Child])
  children: Child[];
}

在这种情况下,我们不会有通用的 Child 对象,也不会将它们用作独立的 Schema。

另一种方法是创建Child 架构并在@Prop({type: [childSchema], _id: false}) 中使用它,但这看起来像是开销。

【问题讨论】:

    标签: javascript mongoose nestjs typescript-decorator nestjs-mongoose


    【解决方案1】:

    描述您的案例的 quik 示例是:

    import { Document, Schema as MongooseSchema } from 'mongoose';
    import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
    
    class GuildMember {
      @Prop({ type: String, required: true, lowercase: true })
      _id: string;
    
      @Prop({ required: true })
      id: number;
    
      @Prop({ required: true })
      rank: number;
    }
    
    @Schema({ timestamps: true })
    export class Guild extends Document {
      @Prop({ type: String, required: true, lowercase: true })
      _id: string;
    
      @Prop({ type: MongooseSchema.Types.Array})
      members: GuildMember[]
    }
    
    export const GuildsSchema = SchemaFactory.createForClass(Guild);
    

    因为在嵌套模式中,您没有在 prop 装饰器中定义类型,而只是告诉该字段是一个数组并使用 TypeScript 验证类型

    【讨论】:

      猜你喜欢
      • 2020-10-26
      • 2016-10-24
      • 2022-10-06
      • 2021-07-08
      • 2021-06-29
      • 1970-01-01
      • 2021-10-20
      • 2022-09-23
      • 2021-10-15
      相关资源
      最近更新 更多