Hello Developers,
I've an issue with the usage of virtual properties. I got one parent document (e.g. Users) which embeds another document (e.g. Stats). To do so, I've followed the instructions from documentations (https://docs.nestjs.com/techniques/mongodb#subdocuments).
The sub-document has two properties: wins and losses. With these values I want to create a virtual property on the sub-document called winRate. When I try to get the users document, the stats are included, but the winRate is still missing, even when it is defined in subdocuments schema.
Parent Definition of Sub-Document
@Prop({ type: [RankedStat] })
rankedStats: RankedStat[];
Virtual Property inside Sub-Document
@Virtual({
get: function (this: RankedStat) {
return (this.wins / (this.wins + this.losses)) * 100;
}
})
winRate: number;
I know, that I have to set toJSON: { virtuals: true } inside of the schema options, but as already mentioned, the winRate is not visible in the output. Somehow, if I define the virtual property on the parents document schema (without decorators, after schema) it is working, but honestly, I am not happy with this as I'd like to use the decorators and in my opinion, the solution below mixes responsibility.
Current working solution, but unhappy with it
UserSchema.path('rankedStats').schema.virtual('winRate').get(function(this: RankedStat) {
return (this.wins / (this.wins + this.losses)) * 100;
});
Is it a bug I've figured out or do I miss something? Oh, just to clarify: I use @nestjs/mongoose and I'd like to stick with it.
Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Reactive Programming).