NestJS - Mongoose discriminator key won't be filled up automatically

Viewed 259

The discriminatorKey won't be filled up automatically. In other words, I cannot find the kind field on the saved document.

Database Module

@Global()
@Module({
  imports: [
    MongooseModule.forFeature([
      {
        name: User.name,
        schema: UserSchema,
        discriminators: [
          { name: Fan.name, schema: FanSchema },
        ],
      },
    ]),
  ],
  exports: [MongooseModule],
})
export class DatabaseModule {}

User Schema

@Schema({ discriminatorKey: 'kind' })
export class User {
  @Prop({ enum: [Fan.name], required: true })
  kind: string;

  @Prop()
  displayName: string;
}

export const UserSchema = SchemaFactory.createForClass(User);

Fan Schema

@Schema()
export class Fan {
  kind: string;

  displayName: string;
}

export const FanSchema = SchemaFactory.createForClass(Fan);

Save a Document

const userObj = new Fan();
userObj.displayName = "Sam";

return this.userModel.create(userObj);
1 Answers

I was injecting the wrong model, that's why the discriminatorKey couldn't be filled up automatically.

Wrong Use

constructor(@InjectModel(User.name) private readonly userModel: Model<User>) {}

Correct Use

constructor(@InjectModel(Fan.name) private readonly fanModel: Model<Fan>) {}
Related