Short version: How can nested GraphQL queries be resolved when the GraphQL Schema differs from the data stored in a MongoDB database?
In our application, each user in our database has an array of foreign keys referencing other documents, such as "pets," which are stored in a separate collection.
{
"humans": [
{
"id": "1",
"name": "bob",
"pets": [
"jBWMVGjm50l5LGwepDoty1",
"jBWMVGjm50l5LGwepDoty12"
]
}
]
}
We have a GraphQL API in front of this database, and we are working on writing resolvers to handle nested queries. However, the challenge is that our GraphQL schema does not align with the database schema. For example, within the Human
type, the pets
field expects an array of pet objects:
type Human {
id: ID!
name: String!
pets: [Pet!] # This should be an array of pet objects...
gender: String!
hair: String!
favoriteNum: Int!
alive: Boolean!
createdAt: Int!
}
Currently, the resolver for humans retrieves a human by ID from the database and returns that human:
human(parent, { input }, { models }) {
return models.Human.findOne({ id: input.id });
}
The issue arises because the returned human object from the database does not match the GraphQL schema. The array of "pets" is actually an array of IDs rather than objects. How should we properly resolve this query?
We have attempted to include another database call for the human's pets within the humans resolver. However, this approach leads to unnecessary data retrieval if a query is made only for the human's name...
A similar dilemma would arise if our pets also had foreign keys! What is the best solution to address this issue?