Generate Graphql Type from mongoose schema with subfields Generate Graphql Type from mongoose schema with subfields mongoose mongoose

Generate Graphql Type from mongoose schema with subfields


Like you said, when you write your GraphQL schema, history will need to be a separate type, as will probably Order and Restaurant. Using Apollo, the schema type definitions would look something like:

type User {  # additional fields  history: [Record!]!}type Record {  orders: [Order!]!  restaurant: Restaurant}

In addition to the type definitions above, you would also provide a resolver for User. In this case, the resolver would simply return User.findOne() (or however you normally get the User object from your database).

Here's the neat part: you may not even need resolvers for Order, Restaurant or even History. When you don't specify a resolver, GraphQL will use a default resolver that happily uses the object it's passed (whatever chunk of the User object you would pass in your resolver for the User type). If it finds keys in that object that match the fields in you specified in your GraphQL schema's type definition, it will populate those fields and ignore everything else.

Of course, if you need additional control (maybe your object keys and field names don't match), you can always still write the resolver yourself.