在GraphQL和Apollo中检索数组

时间:2018-08-25 00:02:16

标签: mongodb reactjs 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();
  }

该数组是“动作”下的字符串数组...在查询中获得帮助的任何帮助都将受到赞赏...这是前端的当前查询...使用Apollo Boost

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

1 个答案:

答案 0 :(得分:0)

不确定它是否仍然有用,我还没有重新创建代码,但是问题可能是,您将“运动”作为“字符串”返回,而不是输出对象类型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

进行检查