Search code examples
node.jstypescriptmongodbmongoosenestjs

NestJS Mongoose extend Schema and override property of parent


I want my Class B to extend a Class A. This works as expected, but now I need to override a property of Class A in Class B.

To be specific, I have to make the property from Class A optional for Class B:

export class B extends A {
  // This property is available in Class A
  @Prop({ required: false, index: true })
  @ApiProperty()
  propertyToOverride: number;
}

Solution

  • I asked about this in NestJS's Discord, and this is the answer I got, from the moderator Scott (Scott (EN-DE)#0052):

    There is no overriding of prop properties. And, the classic inheritance of schema definitions doesn't work either, i.e. with overriding. If you are extending from a schema class, you can only add additional fields to it in your new class. So, it is a reusability tool and not a polymorphism tool. If you need polymorphism, then you need to look at discriminators.

    So unfortunately it seems there is no way to do it with inheritance currently :(