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?
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);
}
}
}
Thanks for the reply! I'm wondering is this the general design pattern for working with GraphQL and databases like MongoDB?
For any future reference, const serviceDetails = await Sevice.findByID(serviceID) is what worked as this method is called for each AppointmentBooking which holds its own serviceID.
medium.com/paypal-engineering/…. This blog post will give better understanding with the patterns,
Great! Thanks for the help!