GraphQL关系返回null

时间:2019-02-18 14:49:21

标签: node.js mongodb graphql

我正在学习graphql并使用mongodb数据库开发一个简单的API。我不知道为什么在我的模式中声明的关系不起作用:

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

当我运行此查询时:

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

这就是我得到的:

"People": [
      {
        "firstName": "John",
        "lastName": "DOE",
        "service": null
      },
      {
        "firstName": "Jane",
        "lastName": "DOE",
        "service": null
      }
]

有什么想念我的地方吗?

1 个答案:

答案 0 :(得分:0)

问题在于您的解决者:

根据回购,您链接的查询如下所示:

const People = require('../database/people');
const Service = require('../database/service');
const queries = {
    People: () => People.find({}),
    ...
    Service: () => Service.find({}),
    ...
  };

module.exports = queries;

People模式如下:

const mongoose = require('mongoose');

const Schema = mongoose.Schema;
const peopleSchema = new Schema({
    Xid: { type: String },
    firstName: { type: String },
    lastName: { type: String },
    email: { type: String },
    apps: { type: Array },
    serviceId: { type: String },
    service: { type: Schema.Types.ObjectId, ref: 'service' }
},{ versionKey: false })

module.exports = mongoose.model('people', peopleSchema);

People.find()将仅返回服务_id,但不会返回整个服务对象。这就是为什么您在回复中得到null的原因。

在People中实现的GraphQL关系只有一个Service Type服务,而您从数据库中回来时却有一个_id

您有2种解决方案:

A)查询“人员”时也要检索“服务”对象。在这种情况下,您需要使用猫鼬populate函数: People: () => People.find({}).populate('service'),

以上内容将为People提供引用的Service对象(而不仅仅是_id)

由于您在架构中使用id而不是_id,因此上述内容是不够的,您需要使用以下内容来创建id字段以返回每项服务

People: async () => {
      const people = await People.find({}).populate('service').exec()
      return people.map(person => ({
        ...person._doc,
        id: person._doc._id,
        service: {
          ...person._doc.service._doc,
          id: person._doc.service._doc._id,
        },
      }))
    }, return people
}

以上内容非常令人困惑。我强烈建议您使用解决方案(B)

有关populate()的文档:https://mongoosejs.com/docs/populate.html

B)为type解析器用户

// Type.js
const Service = require('../database/service');
const types = {
    People: {
      // you're basically saying: In People get service field and return...
      service: ({ service }) => Service.findById(service), // service in the deconstructed params is just an id coming from the db. This param comes from the `parent` that is People
    },
   Service: {
     id: ({_id}) => _id, // because you're using id in your schema
},
  };

module.exports = queries;

有关此选项实施的说明: