简体   繁体   English

如何使用来自@nestjs/mongoose 的@Prop 装饰器添加嵌套的对象数组

[英]How to add nested array of objects with @Prop decorator from @nestjs/mongoose

When I use a nested array of object in prop decorator:当我在道具装饰器中使用 object 的嵌套数组时:

@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);

I get an error:我收到一个错误:

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

How can I fix this if I need to use @Prop({_id: false}) (to keep the nested schema independent)?如果我需要使用@Prop({_id: false}) (以保持嵌套模式独立),我该如何解决这个问题?


If we change a prop decorator to @Prop([Child]) it works, however we need to disable _id for nested object with:如果我们将道具装饰器更改为@Prop([Child])它可以工作,但是我们需要禁用嵌套 object 的_id

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

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

And in this case we won't have generic Child object and we won't to use them as an independent Schema.在这种情况下,我们不会有通用的 Child object,我们不会将它们用作独立的 Schema。

Another way is to create Child schema and use it in @Prop({type: [childSchema], _id: false}) , but that looks like an overhead.另一种方法是创建Child模式并在@Prop({type: [childSchema], _id: false})中使用它,但这看起来像是开销。

a quik example that describe your case is:一个描述您的案例的 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);

because in nested schema you don't have yo define type INSIDE the prop decorator but only tell that this field is an array and validate the type using TypeScript因为在嵌套模式中,您没有在道具装饰器内定义类型,而只告诉该字段是一个数组并使用 TypeScript 验证类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM