Warm tip: This article is reproduced from serverfault.com, please click

How to display nested graphql object datatypes given mongoDB objectID?

发布于 2020-11-30 02:09:02

I am writing an app with GraphQL and mongoose. I created a function to get all bookings inside MongoDB. A booking object contains a reference to another object called Service. When I store a booking, it will store the associated service object as an ObjectID in MongoDB. When I make a query in graphql to get all the bookings, graphql does not services and their field types since graphql only receives an objectID. How can I fix graphql?

Error message returned for graphql

All the bookings are inside the database but user is represented as an objectID

GraphQL datatype definitions

Resolver in question making the query

The graphql function declaration called createAppointmentBookings

Questioner
c0caDJ
Viewed
0
Indragith 2020-11-30 18:09:13

You need to write a resolver for the serviceType in AppointmentBooking.

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);
    }
  }
}