【问题标题】:How to define GraphQLObjectType for a nested object or list of objects in the same parent object如何为嵌套对象或同一父对象中的对象列表定义 GraphQLObjectType
【发布时间】:2018-10-11 12:42:51
【问题描述】:

对于我的 MongoDB 对象,我有一个架构,其中有很多嵌套数据。

然而,我在 GraphQL 中完美地实现了查询以获取数据,但我无法获取嵌套数据,因为我无法定义类型。

fields() {
        return {
            name: {
                type: GraphQLString,
                description: 'Name of the person'
            },
            age: {
                type: GraphQLString,
                description: 'Age'
            },
            documents: { // what to do here
                type: new GraphQLList(),
                description: 'All documents for the person'
            }
       }
}

原始数据是这样的。

{
    "_id" : ObjectId("5ae1da5e4f00b5eee4ab84ee"),
    "name" : "Indira Gandhi International Airport",
    "age" : 54,
    "documents" : [
        {
             "doc_name" : "personal card",
             "doc_url" : "http://",
             "status" : true
        },
        {
             "doc_name" : "bank card",
             "doc_url" : "http://",
             "status" : true
        }
     ],
    "latitude" : "",
    "longitude" : "",
    "timezone" : "Asia/kolkata"
    .......
}

我是 graphQL 的新手,请帮忙。

【问题讨论】:

    标签: node.js mongoose graphql graphql-js


    【解决方案1】:

    我相信您在这里尝试做的是让您的文档字段成为文档列表。为此,您需要创建一个“文档”GraphQLObjectType 以传递到您的文档字段中的new GraphQLList()。像这样:

    const DocumentType = new GraphQLObjectType({
      name: 'DocumentType',
      fields: {
        doc_name: {
          type: GraphQLString
        },
        doc_url: {
          type: GraphQLString
        },
        status: {
          type: GraphQLBoolean
      }
    });
    

    然后,一旦你创建了它,无论是在同一个文件中(或在不同的文件中并必须导入)并具有正确的依赖项,你就可以将它插入到上面发布的代码中,如下所示:

    fields() {
            return {
                name: {
                    type: GraphQLString,
                    description: 'Name of the person'
                },
                age: {
                    type: GraphQLString,
                    description: 'Age'
                },
                documents: {
                    type: new GraphQLList(DocumentType),
                    description: 'All documents for the person'
                }
           }
    }  
    

    我希望这会有所帮助。

    【讨论】:

    • 谢谢@ericAbour,这个解决方案有效。但是当子节点是复杂对象的列表时,又出现了另一个问题。即如果文件:[名称:“”,网址:“”,标签:[“t1”,“t2”]];我实现了你的解决方案,数据来回调。但它没有解决。仍然显示为 null 的文档
    • 您应该能够对应用于文档的标签遵循相同的模式。 DocumentType 中的 tags 字段应该是另一个 GraphQLList 链接到您定义的 TagType
    • 谢谢 Eric,一切都很好,因为我有一个字段名 'type"。 },现在一切正常。BDW 能否指导我完成 GraphQL 查询中的过滤器、分页实现。
    • 很高兴听到我能为您提供帮助。过滤器和分页比我在这里解释的要多。这里有一些参考:howtographql.com/graphql-js/8-filtering-pagination-and-sortinggraphql.org/learn/pagination
    • 我真的很感激。我一直在寻找一个多小时的答案,你成功了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-20
    • 2018-10-16
    • 2016-05-26
    • 2019-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多