簡體   English   中英

如何使用來自@nestjs/mongoose 的@Prop 裝飾器添加嵌套的對象數組

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

當我在道具裝飾器中使用 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);

我收到一個錯誤:

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

如果我需要使用@Prop({_id: false}) (以保持嵌套模式獨立),我該如何解決這個問題?


如果我們將道具裝飾器更改為@Prop([Child])它可以工作,但是我們需要禁用嵌套 object 的_id

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

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

在這種情況下,我們不會有通用的 Child object,我們不會將它們用作獨立的 Schema。

另一種方法是創建Child模式並在@Prop({type: [childSchema], _id: false})中使用它,但這看起來像是開銷。

一個描述您的案例的 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);

因為在嵌套模式中,您沒有在道具裝飾器內定義類型,而只告訴該字段是一個數組並使用 TypeScript 驗證類型

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM