![](/img/trans.png)
[英]NestJs Graphql (Code first with CLI Plugin)+ Mongoose cannot resolve "../../../../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.