I'm learning GraphQL and building an app for end users to input an insurance plan and return doctors in their area that accept the insurance they've selected. I'm attempting to push an array of "docId"s and "insId"s into my mutation, so that each Doctor and each Plan has an array of plans accepted and doctors accepting, respectively.
Here is the Mutation setup:
// Must find a way to add an array of 'docId's and 'insId's
// to their respective mutations.
const Mutation = new GraphQLObjectType({
name: 'Mutation',
fields: {
addDoctor: {
type: DoctorType,
args: {
doctorName: { type: GraphQLString },
city: { type: GraphQLString },
specialty: { type: GraphQLString },
insId: { type: GraphQLID }
},
resolve(parent, args){
let doctor = new Doctor({
doctorName: args.doctorName,
city: args.city,
specialty: args.specialty,
insId: [args.insId]
});
return doctor.save();
}
},
addPlan: {
type: InsuranceType,
args: {
insName: { type: GraphQLString },
usualCoPay: { type: GraphQLString },
docId: { type: GraphQLID }
},
resolve(parent, args){
let plan = new Plan({
insName: args.insName,
usualCoPay: args.usualCoPay,
docId: [args.docId]
});
return plan.save();
}
}
}
})
Here are the mongoose models:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const doctorSchema = new Schema({
doctorName: String,
city: String,
specialty: String,
insId: Array
})
module.exports = mongoose.model('Doctor', doctorSchema);
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const planSchema = new Schema({
insName: String,
usualCoPay: String,
docId: Array
});
module.exports = mongoose.model('Plan', planSchema);
When attempting to add an array of each id in GraphiQL like this:
mutation {
addPlan(insName:"United", usualCoPay: "$30", docId: ["5e37548b42037513e5dfc790", "5e37544642037513e5dfc78f", "5e3754b842037513e5dfc791"]){
insName
usualCoPay
}
}
I'm getting
{
"errors": [
{
"message": "Expected type ID, found [\"5e37548b42037513e5dfc790\", \"5e37544642037513e5dfc78f\", \"5e3754b842037513e5dfc791\"].",
"locations": [
{
"line": 2,
"column": 57
}
]
}
]
}
Any ideas as to what I need to change to ensure that i'm able to put in an array of each ID? Please let me know if you need anything else from my current codebase.
In GraphQL, List is a wrapping type that wraps another type and represents a list or array of the type it wraps. So a List of Strings ([String]
) would represent an array of strings. If your argument takes a list of IDs, then your type for the argument should be [ID]
. Programmatically, we write this as:
new GraphQLList(GraphQLID)
You may also want to prevent nulls from being included in the provided list, in which case we'd do:
new GraphQLList(new GraphQLNonNull(GraphQLID))
or if the entire argument should never be null:
new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(GraphQLID)))