问题在于您的解决方案:
根据您链接的存储库,您的查询如下所示:
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) 您还想在查询 People 时检索 Service 对象。在这种情况下,您需要使用猫鼬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;
关于此选项的实施说明: