18

Trying to make my first graphQL server, here's what I have written so far.

https://gist.github.com/tharakabimal/7f2947e805e69f67af2b633268db0406

Following error pops up on GraphQL when I try to filter the users by username.

Error on GraphQL

The error occurs in the users field in UserQueriesQL.js.

Is there anything wrong the way I pass arguments on the resolve functions?

user: {
type: UserType,
args: { 
  username: {
    name: 'username',
    type: new GraphQLNonNull(GraphQLString)
  }
},
resolve: function(parentValue, args) {
  return User.find( args ).exec();
}
AndrewL64
  • 15,794
  • 8
  • 47
  • 79
King Julian
  • 239
  • 1
  • 3
  • 5
  • The error means you are returning `null`, but with `type: new GraphQLNonNull(GraphQLString)` you declared that there may never be returned `null` for the username. Either return something else than `null`, or declare the type as `type: new GraphQLString()` – marktani Feb 23 '17 at 13:49
  • `User.find` will resolve to an array, but GraphQL is expecting an object instead. Please see Common Scenario #2 in [this answer](https://stackoverflow.com/questions/56319137/why-does-a-graphql-query-return-null/56319138#56319138). – Daniel Rearden Jun 01 '19 at 16:24

2 Answers2

6

As I am beginner into GraphQL, even I ran into this issue. After going through each file individually I found that I forgot to import into my resolvers

import User from './User';
**import Post from './Post';**

const resolvers = [User, **Posts**];

Maybe this will help!

Neville Dabreo
  • 309
  • 3
  • 5
1
user: {
type: UserType,
args: { 
  username: { type: new GraphQLNonNull(GraphQLString) }
},
resolve: function(parentValue, args) {
  return User.find( args ).exec(); // User.find({username: 'some name'}).exec(); 
// will work as matches your mongoose schema
}

Previously, in the args you are providing an an object with nested object username so,

args: {  // this won't match your mongoose schema field as it's nested object
  username: {
    name: 'username',
    type: new GraphQLNonNull(GraphQLString)
  }
}

so when the user queries and provides args then your args would be { username: { name: 'abcd' } }

// args = {username: {name: 'abcd'}}

and resolve() is executing User.find({username: {name: 'abcd'}}).exec();

/* searching for username{} object, but
your mongoose schema is username: String */

which doesn't match your database fields, which will always return an empty array [],also which will not match your GraphQL field type, as it is GraphQLNonNull

after viewing the gist the problem is with rootquery

the problem is with rootquery

let RootQuery = new GraphQLObjectType({
    name: 'RootQueryType',
    fields: () => ({
        users: { type:UserQueries.users, resolve: UserQueries.users }
        user: { type: UserQueries.user, resolve: UserQueries.user }
    })
});
parwatcodes
  • 6,669
  • 5
  • 27
  • 39