首页 > 解决方案 > Nestjs - Mongoose - 虚拟字段 - 无法在 graphql 操场上查询

问题描述

我正在尝试在nestjs-mongoose 中创建一个虚拟字段。该代码没有显示任何错误,但我无法在 graphql 游乐场中查询该虚拟字段。

我厌倦了使用 schema.virtual("virtualFieldName") 添加虚拟字段。然后我为各自的模式启用了 {virtuals: true} 。但仍然无法查询该字段。

我是否需要在 DTO 文件中添加任何内容?

Entity.ts / 架构文件

@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';
});```

标签: mongodbmongoosegraphqlmongodb-querynestjs

解决方案


您必须创建一个类型或另一个类,而不是使用实体。实体虚拟不在实体文档类中。


推荐阅读