GraphQL嵌套查询返回空字段

时间:2019-02-14 10:40:36

标签: graphql

我正在尝试学习GraphQL(和node.js和MongoDB等)。我无法获得这个简单的嵌套查询来返回结果:

query getLocationByPerson {
   People {
        firstName
        lastName
        service {
        location
      }
   }
}

我只获得第一级字段,例如:

{
  "data": {
    "People": [
      {
        "firstName": "xxx",
        "lastName": "XXXXX",
        "service": null
      }
}

这是我的模式:

type Query {
  People: [PeopleObject]!
  PeopleByName(lastName: String!): [PeopleObject]
  PeopleByID(id:ID!): [PeopleObject]
  Service: [ServiceObject]
  ServiceByID(id:ID!): [ServiceObject]
}
type PeopleObject {
    id: ID!
    Xid: String!
    firstName: String!
    lastName: String!
    email: String!
    serviceId: String
    apps: [String]
    service: [ServiceObject]
}
type ServiceObject {
    id: ID!
    name: String!
    location: String!
}

还有我的解析器:

const queries = {
    People: () => People.find({}),
    PeopleByName: (root,args,context,info) => People.find({lastName: args.lastName}),
    PeopleByID: (root,args,context,info) => People.find({_id: args.id}),
    Service: () => Service.find({}),
    ServiceByID: (root,args,context,info) => Service.find({_id: args.id})
  };

知道我在做什么错吗?

2 个答案:

答案 0 :(得分:0)

您需要传递服务中的位置对象的引用,该引用与您的猫鼬模型相同(我假设您使用的是猫鼬)。传递引用后,您可以在服务查询Refer this

中添加populate(refernce).exec()

答案 1 :(得分:0)

您的语法对于从graphql获取任何数据都非常有用

type Query {
  People: [PeopleObject]!
}
type PeopleObject {
    id: ID!
    Xid: String!
    firstName: String!
    lastName: String!
    email: String!
    serviceId: String
    apps: [String]
    service: [ServiceObject]
}
type ServiceObject {
    id: ID!
    name: String!
    location: String!
}

为简单起见

type Query {
  People: [{
    id: ID!
    Xid: String!
    firstName: String!
    lastName: String!
    email: String!
    serviceId: String
    apps: [String]
    service: [{
        id: ID!
        name: String!
        location: String!
    }]
}]!
}

但是您只返回了人

People: () => People.find({}),

您应该返回服务数组对象以使用People获取该返回对象

People: () =>返回类似下面的结果。

[{
    id: '5c5ac87e5e4d85ae77de9c50'
    Xid: 'xx'
    firstName: 'yyy'
    lastName: 'zzz'
    email: 'xxx@gmail.com'
    serviceId: '5c5ac87e5e4d85ae77de9c51'
    apps: ['testing', 'google']
    service: [{
        id: 5c5ac78d5e4d85ae77de9c4f,
        name: 'Tester',
        location: 'US America',
    }, {}]
}, {}]

如果使用猫鼬,请使用aggregation从mongoBD中获取数据。

相关问题