简体   繁体   中英

Nest JS setting up a schema with fields as nested objects

I have such model in Mongo:

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

In schema:

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

Get this error: [在此处输入图片描述](https://i.stack.imgur.com/LBNrD.png)

How can i resolve it?

Need to use nested objects in my schemas with using GraphQl. @Field decorator doesn't work with nested object fields correctly

You will have to build the positions @ObjectType first, then use it in Settings class

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

  @Field(() => Number)
  row: number
  ...
}

And then change your Settings object to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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