Home > Back-end >  how to set multi type for one field (with type of array or object) of schema (Typescript , NestJs)
how to set multi type for one field (with type of array or object) of schema (Typescript , NestJs)

Time:11-21

I want to set multi type for one field of my schema

like this:

@Schema({ validateBeforeSave: true, _id: false })
class example1 {
  a: string;
  b: number;
}

@Schema({  validateBeforeSave: true, _id: false })
class example2 {
  a: string;
  b: number;
}

@Schema({ collection: 'user', validateBeforeSave: true, timestamps: true })
export class User extends Document {
  @Prop({ type: example1 | example2 })
  firstProp: string;

  @Prop({ type: example1[] | example2[] })
  secondProp: example1[] | example2[];
}

I want property with two type and an array with two or more type and i want to that mongoDB validate my schema

CodePudding user response:

you can use refpath for multiple object type on this

and for multiple array type you can do like this:

@Prop([
    { type: example1 },
    { type: example2 },
  ])
  payMethod?: PayMethod[];

it's equal to this

@Prop({
  type:[
    { type: example1 },
    { type: example2 },
  ]
})
  payMethod: PayMethod[];
  • Related