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

Time:10-02

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

}

CodePudding user response:

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);
  • Related