繁体   English   中英

将 NestJS GraphQL 插件与 Mongoose 一起使用

[英]Using the NestJS GraphQL Plugin with Mongoose

NestJS has a graphql plugin ( https://docs.nestjs.com/graphql/cli-plugin ) which generates the the TypeScript metadata for ObjectTypes/InputTypes/etc automatically in order to cut down on biolerplate code. 如果您想覆盖自动生成的属性,您只需将显式 @Field() 添加到相关属性即可。

这在将 class 属性声明为默认标量类型(如下面未注释的 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 package 类型的任何属性(例如示例中的 _id 或hireDate),即使您明确分配了@Field(),运行/构建程序也会失败。

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

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

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

谢谢。

只需将类型定义为 GraphQL 的string ,您可以使用type: () => ObjectId来确保 mongoose 使用 ObjectId。

ObjectId 无论如何都不能通过 JSON 传输,所以最好使用字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM