Reputation: 674
How can I return the data from multiple collections from Graphql ?
const jobsCollection = db.collection('jobs');
const companysCollection = db.collection('company');
import {
GraphQLList,
GraphQLObjectType,
GraphQLSchema,
GraphQLString,
GraphQLInt,
GraphQLFloat,
GraphQLEnumType,
GraphQLNonNull
} from 'graphql';
const Company = new GraphQLObjectType({
name: 'Company Name',
description: 'test',
fields: () => ({
_id: {type: GraphQLString},
name: {type: GraphQLString},
address : {type: GraphQLString}
}
})
});
Through the below query I want to query for company collection too. How can I do this?
const Job = new GraphQLObjectType({
name: 'job',
description: 'test',
fields: () => ({
_id: {type: GraphQLString},
name: {type: GraphQLString},
skill_set : {type: GraphQLString},
company: {type: Company}
}
})
});
## Through the below query I want to query for company collection too. How can I do this? ##
const Query = new GraphQLObjectType({
name: "Queries",
fields: {
jobs: {
type: new GraphQLList(Job),
resolve: function(rootValue, args, info) {
let fields = {};
let fieldASTs = info.fieldASTs;
fieldASTs[0].selectionSet.selections.map(function(selection) {
fields[selection.name.value] = 1;
});
return jobsCollection.find({}, fields).toArray();
}
}
}
});
Upvotes: 2
Views: 3420
Reputation: 7172
The schema and queries in GraphQL don't care if your data is in one, two or ten collections. You can even have data on many different servers, in different databases. The GraphQL server does joins (i.e. combining data from different collections in your case) by following the relationships you defined in your schema, and then running what's called a resolve function for each field in your response to get the actual data.
So your query will look something like this:
query {
jobs {
_id
company {
name
}
}
}
You already have a resolve function for jobs, now you simply need to define another one for company. Presumably your jobs collection either contains the company (and name) in its documents, or it contains the _id of the company, so all you have to do in the company resolve function is something like this:
resolve(job, args, context, info){
return companyCollection.findOne({ _id: job.companyId });
}
I wrote a longer medium post that explains GraphQL execution in more detail. You can find it here.
Upvotes: 2