【问题标题】:How to display nested graphql object datatypes given mongoDB objectID?如何在给定 mongoDB objectID 的情况下显示嵌套的 graphql 对象数据类型?
【发布时间】:2021-03-12 00:04:50
【问题描述】:

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

【问题讨论】:

    标签: mongodb graphql


    【解决方案1】:

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

    【讨论】:

    • 感谢您的回复!我想知道这是使用 GraphQL 和 MongoDB 等数据库的通用设计模式吗?
    • 对于任何将来的参考, const serviceDetails = await Sevice.findByID(serviceID) 是有效的,因为每个 AppointmentBooking 都拥有自己的 serviceID。
    • medium.com/paypal-engineering/…。这篇博文将更好地理解这些模式,
    • 太棒了!感谢您的帮助!
    猜你喜欢
    • 2018-10-21
    • 1970-01-01
    • 1970-01-01
    • 2019-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-30
    相关资源
    最近更新 更多