【问题标题】:Nest JS setting up a schema with fields as nested objectsNest JS 将字段设置为嵌套对象的模式
【发布时间】:2023-01-07 05:32:08
【问题描述】:

我在 Mongo 中有这样的模型:

{
  ...
  settings: {
    positions: [
      {
       column: number,
       row: number,
       buttonId: (ref to Button model)
      }
    ]
  }
}

在架构中:

@Schema({ _id: false })
@ObjectType()
class Settings {
  @Field(() => [Object])
  @Prop({ type: [{ column: Number, row: Number, buttonId: String }] })
  positions: { column: number; row: number; buttonId: string };
}

const SettingsSchema = SchemaFactory.createForClass(Settings);

@Schema()
@ObjectType()
export class Keyboard {
  @Field(() => ID)
  _id: string;

  @Field(() => User)
  @Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'User' })
  author: User;

  @Field(() => Group, { nullable: true })
  @Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'Group' })
  group?: Group;

  @Field(() => Settings, { nullable: true })
  @Prop({ type: SettingsSchema })
  settings?: Settings;
}

export const KeyboardSchema = SchemaFactory.createForClass(Keyboard);

得到这个错误:

我该如何解决?

需要使用 GraphQl 在我的模式中使用嵌套对象。 @Field 装饰器不能正确处理嵌套对象字段

【问题讨论】:

    标签: javascript graphql nestjs mongoose-schema nest


    【解决方案1】:

    你必须先建立位置@ObjectType,然后在Settings类中使用它

    @Schema({ _id: false })
    @ObjectType('Position')
    class Position {
      @Field(() => Number)
      column: number
    
      @Field(() => Number)
      row: number
      ...
    }
    

    然后将您的 Settings 对象更改为

    @Schema({ _id: false })
    @ObjectType('Settings')
    class Settings {
      @Field(() => [Positions])
      positions: Positions[]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-08
      • 1970-01-01
      • 2017-01-25
      • 1970-01-01
      • 1970-01-01
      • 2019-03-28
      • 2021-07-26
      • 2021-09-03
      相关资源
      最近更新 更多