【发布时间】:2021-03-12 00:04:50
【问题描述】:
我正在使用 GraphQL 和 mongoose 编写应用程序。我创建了一个函数来获取 MongoDB 中的所有预订。预订对象包含对另一个称为服务的对象的引用。当我存储预订时,它将关联的服务对象作为 ObjectID 存储在 MongoDB 中。当我在 graphql 中进行查询以获取所有预订时,graphql 不提供服务及其字段类型,因为 graphql 仅接收 objectID。如何修复 graphql?
【问题讨论】:
我正在使用 GraphQL 和 mongoose 编写应用程序。我创建了一个函数来获取 MongoDB 中的所有预订。预订对象包含对另一个称为服务的对象的引用。当我存储预订时,它将关联的服务对象作为 ObjectID 存储在 MongoDB 中。当我在 graphql 中进行查询以获取所有预订时,graphql 不提供服务及其字段类型,因为 graphql 仅接收 objectID。如何修复 graphql?
【问题讨论】:
您需要为 AppointmentBooking 中的 serviceType 编写解析器。
Query: {
async getAppointmentBookings() {
...
}
},
Mutation: {
...
},
AppointmentBooking: {
serviceType: async(parent, args, ctx, info) => {
// Here you will get the objectId from the parent that need to query services
// This will call for every object inside the bookings
// Assuming you are storing the objectID for the services in the key servicetype
const serviceId = parent.serviceType;
try {
const serviceDetails = await Sevice.findByID(serviceID) ;
return serviceDetails;
} catch (err) {
throw new Error(err);
}
}
}
【讨论】: