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

标签 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 对象形状相同的突变中,所以我很困惑。预先感谢您!

最佳答案

您无法通过这种方式将输入传递到查询中。当您使用带有占位符的模板文字时,占位符 (${guides}) 内的表达式的结果将被视为字符串。如果 guides 是一个对象(如果它是一个数组,则确实如此),则对其调用 toString(),这会产生字符串 [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有关如何使用变量的更多详细信息。

关于node.js - 如何使用 GraphQL 在嵌套对象上创建突变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55084490/

相关文章:

node.js - 由于方言对象对象不支持错误,Sequelize 迁移失败

node.js - 在带有快速 session 的 NodeJS 中使用安全 cookie 时 session 不会持续存在

JavaScript 对象操作在唯一操作后显示不同键的相同值

javascript - Moustache.js 中的列表和来自 mongodb 的 bson 数据

graphql - NestJS GraphQL 联合循环解析器

python - 从我的 python 代码中进行 graphQL 突变,出现错误

javascript - 查询后如何更新 Apollo 缓存?

node.js - 在reactjs中convert-csv-to-json返回错误

MongoDB,文档或集合之间的关系

node.js - 使用 Mongoose 更新请求正文中的嵌入文档