Search code examples
typescriptmongoosenestjsnestjs-mongoose

How to define dynamic key in object in array of objects with @Prop() decorator in schema? Mongoose, NestJS


I have array of object like this

const array = [
  {key1: value1},
  {key2: value2},
  ...
]

How to define it correctly in schema with @Prop decorator?

@Schema()
export class Entity{

  @Prop()  // Here
  body: ; // and here

}

Solution

  • Would something like this help?

    import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
    
    export type UserDocument = User & Document;
    
    // Any key as string, and value as a number.
    export interface CustomData {
      [key: string]: number;
    }
    
    @Schema()
    export class User {
      @Prop()
      name: string;
    
      @Prop()
      age: number;
    
      @Prop({ type: [Object] })
      customData: CustomData[];
    }
    
    export const UserSchema = SchemaFactory.createForClass(User);