如何使用GraphQL在嵌套对象上创建突变?

时间:2019-03-10 04:42:58

标签: node.js mongodb graphql

我正在尝试创建一个graphql突变,以使用其他对象数组更新一个对象字段。这是我的架构:

    type Guide {
      _id: ID!
      first_name: String!
      last_name: String
      email: String!
      phone: String!
      creator: User!
    }

    input GuideInput {
      _id: ID!
      first_name: String!
      last_name: String
      email: String!
      phone: String!
    }

    type Trip {
      _id: ID!
      name: String!
      description: String
      location: String
      start_date: String
      start_time: String
      duration: Int
      creator: User!
      guides: [Guide!]
      guests: [Guest!]
    }

    input TripInput {
      name: String
      description: String
      location: String
      start_date: String
      start_time: String
      duration: Int
      guides: [GuideInput]
    }

    type RootQuery {
      trips: [Trip!]
      guides: [Guide!]
    }

    type RootMutation {
      updateTrip(tripId: ID!, tripInput: TripInput): Trip
      deleteTrip(tripId: ID!): Trip
      createGuide(guideInput: GuideInput): Guide
      deleteGuide(guideId: ID!): Guide
    }

    schema {
      query: RootQuery
      mutation: RootMutation
    }

我的查询如下:

const requestBody = {
      query: `
        mutation {
          updateTrip(
            tripId: "${tripId}",
            tripInput: {
              guides: ${guides}
            }
          ) {
            guides {
              first_name
              last_name
            }
          }
        }
      `
    }

执行此请求时遇到的错误是:

Expected type GuideInput, found object.
Expected type GuideInput, found Object.

我正在将一系列对象传递给与GuideInput对象具有相同形状的变异,所以我很困惑。预先谢谢你!

1 个答案:

答案 0 :(得分:0)

您不能以这种方式将输入内容传递到查询中。当您将模板文字与占位符一起使用时,占位符(${guides})内的表达式结果被视为字符串。如果guides是一个对象(如果是数组,则为它),则调用了toString(),这将导致字符串[object Object]。您最终得到的字符串看起来像:

tripInput: {
  guides: [object Object]
}

在查询中替换值的正确方法是使用变量,并避免完全使用占位符。您的requestBody看起来会像这样:

const requestBody = {
  query: `
    mutation SomeMutationName($tripId: ID!, $guides: [GuideInput]) {
     updateTrip(
        tripId: $tripId
        tripInput: {
          guides: $guides
        }
      ) {
        guides {
          first_name
          last_name
        }
      }
    }
  `,
  variables: {
    tripId,
    guides,
  },
}

有关如何使用变量的更多详细信息,请参见the official tutorialthe spec

相关问题