首页 > 解决方案 > 将 NestJS GraphQL 插件与 Mongoose 一起使用

问题描述

NestJS 有一个 graphql 插件(https://docs.nestjs.com/graphql/cli-plugin),它自动为 ObjectTypes/InputTypes/etc 生成 TypeScript 元数据,以减少 biolerplate 代码。如果您想覆盖自动生成的属性,您只需将显式 @Field() 添加到相关属性即可。

这在将类属性声明为默认标量类型(如下面未注释的 firstName 和 lastName 属性中)时非常有用。

import { ObjectType, Field } from '@nestjs/graphql';
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Schema as MongooseSchema } from 'mongoose';

@Schema()
@ObjectType()
export class Person {
  // @Field(() => String)
  // @Prop()
  // _id: MongooseSchema.Types.ObjectId;
  @Prop()
  firstName: string;
  @Prop()
  lastName: string;
  // @Field(() => GraphQLISODateTime)
  // @Prop()
  // hireDate?: MongooseSchema.Types.Date;
}

export type PersonDocument = Person & Document;

export const PersonSchema = SchemaFactory.createForClass(Person);

但是,如果您尝试从 mongoose 包中添加任何类型的属性(例如示例中的 _id 或hireDate),即使您明确分配了@Field(),运行/构建程序也会失败。

我还验证了当从nest-cli.json 文件中删除插件(并且@Field() 标记被添加回firstName、lastName)时,mongoose 类型的使用是有效的。

我知道该插件无法在幕后自动识别/将猫鼬类型转换为适当的 @Field() 分配,但我不知道为什么它在显式 @Field() 时查看类型已提供。

有没有办法同时使用 mongoose 类型和 nestjs cli graphql 插件?

谢谢。

标签: mongoosegraphqlnestjs

解决方案


推荐阅读