Getter access data that is Excluded by class-transformer on mongoose Schema

36 views Asked by At

I have the following class

@Schema({ timestamps: true })
export class Event {
  ...

  @Prop({ type: [SponsorSchema], default: [] })
  @Type(() => Sponsor)
  // @Expose({ groups: ['different.group'] }) <--- or this
  @Exclude()
  sponsors: Sponsor[]

  @Expose({ groups: ['event.list'] })
  get total_sponsored(): number {
    return this.sponsors.reduce((total, sponsor) => total + sponsor.value, 0)
  }

  ...
}

The total_sponsored variable just show when sponsors is with Expose() decorator, so when I use Expose() with different groups (or Exclude()), total_sponsored can't access this.sponsors as it is undefined.

I'm using a Interceptor that has the following code:

return plainToInstance(classToIntercept, document, {
    excludeExtraneousValues: true,
    groups: groups
})

Before stepping into the Interceptor, sponsors has data and total_sponsored don't exists. After that, sponsors is undefined and total_sponsored gives and error because it can't use .reduce on a undefined.

How can I access sponsors data for total_sponsored without it showing on the final object (after Interceptor)?

0

There are 0 answers