Reputation: 37
I am trying to create a virtual field in nestjs-mongoose. The code is not showing any error but I was not able to query that virtual field in graphql playground.
I tired adding a virtual field by using schema.virtual("virtualFieldName"). Then I enabled the {virtuals: true} for the respective schema. But still not able to query this field.
Should I need to add anything in DTO file?
Entity.ts / Schema file
@Schema({
collection: 'v3_customer_account_selectors',
timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' },
toJSON: { virtuals: true },
})
@Injectable({ scope: Scope.TRANSIENT })
export class AccountSelectorEntity extends BaseEntity {
@AliasableProp({ alias: '_type', type: AccountSelectorType })
type: AccountSelectorType;
@Prop()
name?: string;
@AliasableProp({ alias: 'last_checked', type: Date })
lastChecked?: Date;
@AliasableProp({
type: SchemaTypes.ObjectId,
alias: 'customer_id',
})
customerId?: Types.ObjectId;
}
export const AccountSelectorEntitySchema = SchemaFactory.createForClass(
AccountSelectorEntity
);
AccountSelectorEntitySchema.set('toJSON', { getters: true, virtual: true });
AccountSelectorEntitySchema.set('toObject', { getters: true, virtual: true });
AccountSelectorEntitySchema.virtual('selector_type').get(function () {
return 'TestReturn';
});```
Upvotes: 1
Views: 733
Reputation: 3388
You must to create a type or another class instead using an entity. Entity virtuals not in entity document class.
Upvotes: 1