我似乎在 AdType 中使用 UserType 时遇到循环依赖问题。
这是我的用户类型文件:UserType
这是我的 AdType 文件:AdType
如果我尝试使用下面的代码,即使我正确导入了 UserType,我也会收到错误“Ad.user 字段类型必须是输出类型,但得到:未定义”。
import { UserType } from '../User/user.graphql.model'
import { UserSchema } from '../User/user.mongoose.model'
const user = {
type: UserType,
resolve(parentValue, args) {
return UserSchema.findById(parentValue.user);
}
};
//------------------------------
// Ad Type
//------------------------------
export const AdType = new GraphQLObjectType({
name: 'Ad',
fields: () => ({
id,
user,
title,
views,
availability,
... more code
如果我在导入 AdType 后尝试在 AdType 中控制台记录 UserType,它会显示未定义,但是当我将其用作:
//------------------------------
// Ad Type
//------------------------------
export const AdType = new GraphQLObjectType({
name: 'Ad',
fields: () => ({
id,
user: {
type: UserType,
resolve(parentValue, args) {
return UserSchema.findById(parentValue.user);
}
},
title,
... more code
它按预期工作,只是不允许我提取代码来分离常量。
我以相同方式导入和使用的所有其他类型都按预期工作,将广告导入用户也可以,但将用户导入广告似乎会中断。两者的代码基本上相同,只是信息不同。