我正在尝试使用Nest.js、GraphQL和MongoDB创建简单的应用程序。我曾使用TypeORM和TypeGraphql生成我的模式并与localhost数据库建立连接,但我无法使用nest start
运行我的服务器,因为我收到了以下错误:
未处理的PromiseRetention警告:错误:无法确定getArticles 的GraphQL输出类型
我不知道为什么会出现这个错误。我的类ArticleEntity
没有任何非主类型,所以应该不会有任何问题。我试图从ArticleEntity
类的文件_id
的@Field()
装饰器中删除() => ID
,但这对没有帮助
文章解析程序
@Resolver(() => ArticleEntity)
export class ArticlesResolver {
constructor(
private readonly articlesService: ArticlesService) {}
@Query(() => String)
async hello(): Promise<string> {
return 'Hello world';
}
@Query(() => [ArticleEntity])
async getArticles(): Promise<ArticleEntity[]> {
return await this.articlesService.findAll();
}
}
文章服务
@Injectable()
export class ArticlesService {
constructor(
@InjectRepository(ArticleEntity)
private readonly articleRepository: MongoRepository<ArticleEntity>,
) {}
async findAll(): Promise<ArticleEntity[]> {
return await this.articleRepository.find();
}
}
文章实体
@Entity()
export class ArticleEntity {
@Field(() => ID)
@ObjectIdColumn()
_id: string;
@Field()
@Column()
title: string;
@Field()
@Column()
description: string;
}
文章DTO
@InputType()
export class CreateArticleDTO {
@Field()
readonly title: string;
@Field()
readonly description: string;
}
如果你需要任何其他评论
ArticleEntity
应该使用@ObjectType
装饰器进行装饰,如文档中所示https://typegraphql.com/docs/types-and-fields.html.
@Entity()
@ObjectType()
export class ArticleEntity {
...
}
对于任何收到此错误并使用枚举的人来说,您可能缺少对registerEnumType
的调用。
在我的案例中,我使用的是@ObjectType
装饰器,但我是从type-graphql
导入的。我改为从@nestjs/graphql
导入,问题得到了解决。
import { ObjectType } from '@nestjs/graphql';
有关GitHub的相关讨论,请参阅此处。
我使用的是MongoDB,我让Query
返回模式而不是模型类。
将@Query((returns) => UserSchema)
更改为@Query((returns) => User)
为我解决了这个问题。
user.schema.ts
@ObjectType()
@Schema({ versionKey: `version` })
export class User {
@Field()
_id: string
@Prop({ required: true })
@Field()
email: string
@Prop({ required: true })
password: string
}
export const UserSchema = SchemaFactory.createForClass(User)
用户解析程序.ts
@Query((returns) => User)
async user(): Promise<UserDocument> {
const newUser = new this.userModel({
id: ``,
email: `test@test.com`,
password: `abcdefg`,
})
return await newUser.save()
}
输出模型类应该用@ObjectType((进行修饰,然后该类的所有属性都将用@Field((进行装饰。对于任何使用自定义输出模型类而不是实体(sequelize、typeorm、prisma等(的人。因为我首先使用数据库实体,所以一切都很好,直到我转向一个更自定义的输出模型。
另一种情况是有人使用A类作为输出,而B类在中使用
export class A{
id: number;
name:string;
childProperty: B
. . . . .
}
export class B{
prop1:string;
prop2:string;
}
在这种情况下,类B也应该用@ObjectType装饰,字段(prop1,prop2(也应该用@字段装饰。