Using the NestJS GraphQL Plugin with Mongoose

Viewed 268

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. If you want to override the automatically generated property you can just add an explicit @Field() to the property in question.

This works great when declaring class properties as default scalar types (as in the uncommented firstName and lastName properties below).

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);

However, if you try to add any properties that are of a type from the mongoose package (like _id or hireDate in the example), running/building the program will fail, even if you explicitly assign a @Field().

I have also verified that the use of the mongoose types works as shown when the plugin is removed from the nest-cli.json file (and @Field() tags are added back to firstName, lastName).

I understand that the plugin would not be able to automatically identify/convert the mongoose types to the appropriate @Field() assignment behind the scenes but I don't know why it is looking at the type at all when an explicit @Field() has been provided.

Is there a way to use both the mongoose types and the nestjs cli graphql plugin together?

Thanks.

1 Answers

Just define the type as a string for GraphQL, and you can use the type: () => ObjectId to ensure mongoose uses an ObjectId.

ObjectId cannot be transferred over JSON anyway, so may as well use string.

Related