首页 > 解决方案 > 如何在 GraphQL 中获取相同的嵌套对象

问题描述

我有一个收集电话的人,他们的领域很少:-

{
    "_id": {
        "$oid": "5f26e8ef969cc80d9710b250"
    },
    "firstName": "xxxxxxx",
    "lastName": "xxxxxx",
    "email": "xxxxxxxx@gmail.com",
    "userName": "xxxxxx",
    "friends": [
       {
          "$numberInt": "2001" // person identity
       }, 
       {
         "$numberInt": "1002" // person identity
       }
    ],
    "personIdentityCount": {
        "$numberInt": "1000"
    }
}

Friends 是一个数组,它具有唯一的人员身份计数,我们可以从中识别人员,这意味着如果我们搜索 1002 个人员身份计数,它将为我们提供人员数据。

我已经创建了一个模式和类型:-

const personType=new GraphQLObjectType({
    name: "Person",
    fields:{
        id: { type: GraphQLID },
        firstName: { type: GraphQLString },
        lastName: { type: GraphQLString },
        email: { type: GraphQLString },
        userName: { type: GraphQLString },
        count: { type: GraphQLInt },
        friends:{
            type: new GraphQLList(PersonType), // getting an error " personType is not defined "
            resolve: (person) => person.friends.map(id => getPersonByPersonIdentityCount(id))
        }
    }
});

我收到 personType 的错误未在朋友类型中定义({ type: new GraphQLList(PersonType)})。

===== GraphQL 架构 =====

const scheam = new GraphQLSchema({
    query: new GraphQLObjectType({
        name: "Query",
        fields: {
            people: {
                type: GraphQLList(personType),
                resolve: async (root, args, context, info) =>
                {
                    return PersonModel.find().exec();
                }
            },
            person: {
                type: personType,
                args: {
                    id: { type: GraphQLNonNull(GraphQLID) }
                },
                resolve: (root, args) => getPersonByPersonIdentityCount(args.id)
            }
        }
    })

});

我想如果我在 graphQl 请求中询问朋友,那么朋友的价值应该会到来。

#预期响应

    person(id:"5f26a1e8034dec6713cbd28e"){
    id,
    firstName,
    friends{
      id,
      firstName,
      lastName
    }
  }
}

我可以通过数据库级​​别解决这个问题,但我想要一个 graphQL 的解决方案。

标签: node.jsgraphql-jsexpress-graphql

解决方案


推荐阅读