【问题标题】:Pass and retrieve array in GraphQL在 GraphQL 中传递和检索数组
【发布时间】:2021-04-21 19:33:24
【问题描述】:

这些天我正在尝试弄清楚 GraphQL,我在后端使用 mongoDB 数据库,示例报告看起来像这样,

{
    "name" : "Sam",
    "age" : 12,
    "results": {
       "maths" : 43,
       "science": 67,
       "history": 89,
    }
}

报告将有一个名为 results 的对象,其中包含多个对象元素

如何定义我的 GraphQL 查询来处理来自结果对象的对象?我似乎找不到可以用于此的对象类型。

我尝试的 GraphQL 突变看起来像这样,

createReport: {
      type: ReportType,
      args: {
        name: {type: GraphQLString},
        age: {type: GraphQLInt},
        results: {type: GraphQLList},
      },
      resolve(parent, args) {
        let report = new reportModel({
          name: args.name,
          age: args.age
          results: args.results
        })

        return investigation.save()
      }
    },

但这似乎不起作用,正确的 GraphQL 对象或处理 mogodb 对象以进行检索和突变的方法是什么?

谢谢

【问题讨论】:

    标签: javascript graphql


    【解决方案1】:

    你应该定义它的类型:

    // resultsType.js
    
    import * as graphql from 'graphql'
    const { GraphQLInputObjectType, GraphQLString } = graphql
    
    export const ResultsType= new GraphQLInputObjectType({
        name: 'resultsType',
        fields: () => ({
            maths: { type: GraphQLInt},
            science: { type: GraphQLInt},
            history: { type: GraphQLInt},
        }),
    })
    
    

    并将您的代码更改为:

    createReport: {
          type: ReportType,
          args: {
            name: {type: GraphQLString},
            age: {type: GraphQLInt},
            results: {type: ResultsType},
          },
          resolve(parent, args) {
            let report = new reportModel({
              name: args.name,
              age: args.age
              results: args.results
            })
    
            return investigation.save()
          }
        },
    

    【讨论】:

    • 感谢您的回答,我会试试这个。另外‘GraphQLObjectType’和‘GraphQLInputObjectType’有什么区别?
    • 我犯了一个突变错误,我们应该使用 GraphQLInputObjectType 而不是 GraphQLObjectType。
    猜你喜欢
    • 2019-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-30
    • 2018-03-13
    • 1970-01-01
    • 2013-07-01
    • 2021-06-30
    相关资源
    最近更新 更多