首页 > 解决方案 > 如何在给定 mongoDB objectID 的情况下显示嵌套的 graphql 对象数据类型?

问题描述

我正在用 GraphQL 和 mongoose 编写一个应用程序。我创建了一个函数来获取 MongoDB 中的所有预订。预订对象包含对另一个称为服务的对象的引用。当我存储预订时,它将关联的服务对象作为 ObjectID 存储在 MongoDB 中。当我在 graphql 中进行查询以获取所有预订时,graphql 不提供服务及其字段类型,因为 graphql 仅接收 objectID。我该如何修复graphql?

为 graphql 返回的错误消息

所有预订都在数据库中,但用户表示为 objectID

GraphQL 数据类型定义

有问题的解析器进行查询

名为 createAppointmentBookings 的 graphql 函数声明

标签: mongodbgraphql

解决方案


您需要为 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);
    }
  }
}

推荐阅读