【问题标题】:Handling nested input-types with type-graphql and typegoose使用 type-graphql 和 typegoose 处理嵌套的输入类型
【发布时间】:2021-02-09 14:46:50
【问题描述】:

我将typegoosetype-graphql 一起使用,当我尝试使用嵌套@InputType() 时,嵌套对象将转换为mongoose.Types.ObjectId()。如何处理嵌套的 InputTypes

这是我的代码(GrandChild 不是猫鼬文档,它是一个简单的对象类型)

@ObjectType()
export class GrandChild {
  @Field()
  name: string;
}

@ObjectType()
export class Child {
  @prop()
  @Field()
  name: string;

  @prop({ type: () => GrandChild })
  @Field(() => GrandChild)
  grandChild: GrandChild;
}

@ObjectType()
export class Parent {
  @prop()
  @Field()
  name: string;

  @prop({ ref: Child })
  @Field(() => Child)
  child: Ref<Child>;
}

@InputType()
export class GrandChildInput {
  @Field()
  name: string;
}

@InputType()
export class ChildInput {
  @Field()
  name: string;

  @Field(() => GrandChild)
  grandChild: GrandChildInput;
}

@InputType()
export class Parent {
  @Field()
  name: string;

  @Field(() => Child)
  child: ChildInput;
}

示例输入:

{
  "name": "Parent A",
  "child": {
    "name": "Child A",
    "grandChild": {
      "name": "GrandChild A"
    }
  }
}

parent查询:

{
  parent {
    name
    child {
      name
      grandChild {
        name
      }
    }
  }
}

当我运行parent 查询时,我得到以下输出

Cannot read property "Child.grandChild" of undefined.

我使用 mongo bash 来获取父文档,这就是我得到的:

db.parent.find():

{
  name: "Parent A",
  child: ObjectId("some-object-id-here")
}

db.child.find():

{
  name: "Child A",
  grandChild: {
    _id: ObjectId("some-object-id-here")
  }  // <-- This is not supposed to be a document
}

如何解决这个问题?

【问题讨论】:

    标签: node.js typescript typegraphql typegoose


    【解决方案1】:

    discord上也问过这个问题,得出的结论是提供的输出不对,找到实际数据后是:

    {
      name: "Child A",
      grandChild: {
        _id: ObjectId("some-object-id-here")
      }
    }
    

    那么问题就很清楚了:GrandChild 类在属性上没有任何 @prop
    (这从一开始就知道,但调查的是为什么是grandChild: ObjectId("some-object-id-here")而不是grandChild: { _id: ObjectId("some-object-id-here") }

    【讨论】:

    • 我尝试在输入类型和对象类型上都使用 @prop 装饰器,但孙子文档仍然只有 _id 字段。
    • 如果你使用 transpile to file 然后运行它,你是否已经尝试清除你的构建?否则我不知道这还有什么问题
    • 我暂时移除了嵌套对象。不确定这是否是 Typegoose 或 Type GraphQL 的问题。感谢您的帮助!
    猜你喜欢
    • 2019-02-07
    • 2020-05-06
    • 2021-04-24
    • 2019-12-27
    • 2019-08-15
    • 2020-01-14
    • 2019-06-18
    • 2020-12-14
    • 2013-04-26
    相关资源
    最近更新 更多