graphqlexpress-graphql

Cant Return Array in Graphql Query


I'm pretty new to graphql and I'm working on a project in nodejs where I am trying to return users when a getUsers query is performed. The issue is that when I test this query in graphql studio, I'm getting an error stating: "GraphQLError: Cannot query field \"users\" on type \"User\". I'm really confused as to why I'm having this issue. I've seen a number of examples where people where able to return just an array and didn't have a problem, but every time I've tried this I end up getting a similar error. Due to this, I've only been able to return a value for a query or mutation when I am super specific such as for my user query:

...
const user = await requireAuth(user)
 return {
      _id: user._id,
      username: user.username,
      firstName: user.firstName,
      email: user.email,
}

Does anyone know why this is happening? I would really appreciate any help or advice. Thank you!

Query getUsers in graphql,

{
  getUsers {
   users
  }
}

Query in user-resolvers.js

getUsers: async(parent, args, context, info) => {
    try {
      let users = await User.find()
      console.log(users)
      // console.log(users) shows all of the users in the format found in type Users 
      return users;
    }
    catch (error) {
      throw error;
    }
  },

schema.js

export default`

type Users {
    _id: ID!
    username: String
    email: String!
    firstName: String
    lastName: String
    basicInfo: [BasicInfo]!
    avatar: String
    date: Date
  }

  type BasicInfo {
    birth_date: String!
    age: Int!
    feet: Int!
    inches: Int!
  }
...
  type Query {
    getUsers: [Users]
  }
...

  schema {
    query: Query
    mutation: Mutation
  }
`;

index.js

import UserResolvers from './user-resolvers.js';
import User from '../../models/User.js';

export default {
  Query: {
    user: UserResolvers.user,
    getUsers: UserResolvers.getUsers,
  },

...
};

Solution

  • In the query you specify the fields you want to return and you don't have a field users, you must only specify fields that exist in your schema:

    {
      getUsers {
        id
        username
        email
        ...
      }
    }
    

    More info here