将 ID 数组添加到 GraphQL 突变

Add an array of IDs to a GraphQL mutation

我正在学习 GraphQL 并构建一个应用程序供最终用户输入保险计划,return 他们所在地区的医生接受他们选择的保险。我正在尝试将 "docId"s 和 "insId"s 的数组推入我的突变中,以便每个 Doctor 和每个 Plan 分别有一组接受的计划和接受的医生。

这里是 Mutation 设置:

// 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();
            }
        }
    }
})

以下是猫鼬模型:

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);

当尝试像这样在 GraphiQL 中添加每个 id 的数组时:

mutation {
    addPlan(insName:"United", usualCoPay: "", docId: ["5e37548b42037513e5dfc790", "5e37544642037513e5dfc78f", "5e3754b842037513e5dfc791"]){
            insName
        usualCoPay
    }
  }

我得到

{
  "errors": [
    {
      "message": "Expected type ID, found [\"5e37548b42037513e5dfc790\", \"5e37544642037513e5dfc78f\", \"5e3754b842037513e5dfc791\"].",
      "locations": [
        {
          "line": 2,
          "column": 57
        }
      ]
    }
  ]
}

关于我需要更改什么以确保我能够放入每个 ID 的数组有什么想法吗?如果您需要我当前代码库中的任何其他内容,请告诉我。

在 GraphQL 中,List 是一个 wrapping 类型,它包装了另一种类型并表示它包装的类型的列表或数组。因此,字符串列表 ([String]) 将表示一个字符串数组。如果您的参数采用 ID 列表,那么您的参数类型应为 [ID]。以编程方式,我们将其写为:

new GraphQLList(GraphQLID)

您可能还想防止空值包含在提供的列表中,在这种情况下我们会这样做:

new GraphQLList(new GraphQLNonNull(GraphQLID))

或者如果整个参数不应该为空:

new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(GraphQLID)))