首页 > 解决方案 > 在 GraphQL 和 Apollo 中检索数组

问题描述

因此,我使用 Graphql 和 apollo 设置了一个 api,并设法将字符串数组导入 mongoDB ...现在我正在使用 Apollo 查询数据以做出反应,并且似乎无法找到如何检索它,因为我得到了

error:[GraphQL error]: Message: String cannot represent an array value: [pushups,situps], Location: [object Object], Path: wods,0,movements 

我的架构设置为:

   const WodType = new GraphQLObjectType({
  name: 'Wod',
  fields: () => ({
    id: { type: GraphQLID },
    name: { type: GraphQLString },
    movements: { type: GraphQLString },
    difficulty: { type: GraphQLString },
    group: {
  type: GroupType,
  resolve(parent, args) {
    return Group.findById(parent.groupId);
  }
}

}) });

我的突变为:

const Mutation = new GraphQLObjectType({
  name: 'Mutation',
  fields: {
    addWod: {
      type: WodType,
  args: {
    name: { type: new GraphQLNonNull(GraphQLString) },
    movements: { type: new GraphQLList(GraphQLString) },
    difficulty: { type: new GraphQLNonNull(GraphQLString) },
    groupId: { type: new GraphQLNonNull(GraphQLID) }
  },
  resolve(parent, args) {
    let wod = new Wod({
      // Use model to create new Wod
      name: args.name,
      movements: args.movements,
      difficulty: args.difficulty,
      groupId: args.groupId
    });
    // Save to database
    return wod.save();
  }

该数组是“运动”下的字符串数组......非常感谢任何有助于将其放入 React 的查询......这是前端的当前查询......使用 Apollo Boost

const getWodsQuery = gql`
  {
    wods {
      id
     name
      movements
      difficulty
    }
   }
 `;

标签: mongodbreactjsgraphqlapollo

解决方案


不确定它是否仍然相关,我没有重新创建代码,但问题可能是,您将“运动”作为“字符串”返回,而不是输出对象类型 Wod 中的字符串数组。这只是基于您传递给突变的参数(即字符串列表)做出的假设。修复应该只是修改 Wood 类型如下

const WodType = new GraphQLObjectType({
  name: 'Wod',
  fields: () => ({
    id: { type: GraphQLID },
    name: { type: GraphQLString },
    movements: { type: new GraphQLList(GraphQLString) },
    difficulty: { type: GraphQLString },
    group: {
  type: GroupType,
  resolve(parent, args) {
    return Group.findById(parent.groupId);
  }
})

请注意,这只是我的假设,因为我不知道您的数据是如何存储的,但根据错误消息它可能是正确的。我写了一篇关于在 GraphQL 模式中实现列表/数组的文章,因为我看到很多人都在为类似的问题而苦苦挣扎。你可以在这里查看https://graphqlmastery.com/blog/graphql-list-how-to-use-arrays-in-graphql-schema


推荐阅读