skip to Main Content

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

2

Answers


  1. 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[];
    
    Login or Signup to reply.
  2. Seems like Mr. Alireza’s answered is pretty decent.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search