【问题标题】:Schema/Resolve for nested objects graphql/mongoose嵌套对象的模式/解析 graphql/mongoose
【发布时间】:2019-12-21 16:51:29
【问题描述】:

我正在使用带有 mongoose 的 graphql,并且我正在尝试以这种形式的 json 访问嵌套对象数组:

"Plans": [
{
  "id": ...
  "name": ...
  "frequency": ...
  "lastExecuted": ...
  "Steps": {
    "Step": [
    {
      "id": ...
      "shortDescription": ...
      "description": ...
      ...
    },
    {...],
}

我创建了一个猫鼬模型:

const PlanModel = Mongoose.model("Plan", {
  name: String,
  frequency: GraphQLString,
  lastExecuted: String,
  Steps: []
})

直觉上我会在数组中插入我的 Stepmodel,但这给了我一个错误。

所以我尝试使用解析器填充数组:

    Plans: {
  type: GraphQLList(PlanType),
  args: getGraphQLQueryArgs(PlanType),
  resolve: (root, args, context, info) => {
    return PlanModel
    .find()
    .populate("Steps")
    .populate("Steps.Step")
    .exec();
  }
},

这是我的计划类型:

const PlanType = new GraphQLObjectType({
  name: 'Plan',
  fields: () => ({
    id: {
      type: GraphQLID
    },
    name: {
      type: GraphQLString
    },
    frequency: {
      type: GraphQLString
    },
    lastExecuted: {
      type: GraphQLString
    },
    maintenanceSteps: {
      type: GraphQLList(StepType)
    },
  })
})

在这种情况下,我的 GraphQL 查询返回一个空数组。我知道这是一个常见问题,但我找不到任何解决我的问题的方法

【问题讨论】:

    标签: json mongoose nested graphql


    【解决方案1】:

    我的问题的解决方案是添加另一种类型:

    const StepsType = new GraphQLObjectType({
      name: 'Steps',
      fields: () => ({
        Step: {
          type: GraphQLList(StepType)
        }
      })
    })
    
    const PlanType = new GraphQLObjectType({
      name: 'Plan',
      fields: () => ({
        _id: {
          type: GraphQLID
        },
        id: {
          type: GraphQLString
        },
        name: {
          type: GraphQLString
        },
        frequency: {
          type: GraphQLString
        },
        lastExecuted: {
          type: GraphQLString
        },
        status: {
          type: GraphQLString
        },
        Steps: {
          type: StepsType
        },
      })
    })
    

    【讨论】:

      猜你喜欢
      • 2017-01-07
      • 2018-08-27
      • 2018-09-02
      • 2018-08-25
      • 1970-01-01
      • 2017-02-14
      • 2017-07-06
      • 2016-05-06
      • 2021-05-24
      相关资源
      最近更新 更多