Search code examples
graphqlapollo

Cannot return null for non-nullable field in graphql


I have a Apollo server query that returns an array of movies based on a userIdvalue:

  moviesFromUser: async (root, args) => {
    const movie = await prisma.movie.findMany({
      where: {userId: args.userId},
    });
    console.log(movie);
    return movie;
  },

In the sandbox I have a query to fetch the movies based on userId:

query moviesFromUser {
  moviesFromUser(userId: 1) {
    original_title
  }
}

When I run this query I see the movies I've requested in the console log of the Apollo server:

[
  {
    id: 251,
    original_title: 'Dune',
    tmdb_id: 2,
    poster_path: 'cDbNAY0KM84cxXhmj8f0dLWza3t.jpg',
    userId: 1
  },
  {
    id: 252,
    original_title: 'Batman',
    tmdb_id: 3,
    poster_path: 'asdadsdasadsadsdas.jpg',
    userId: 1
  }
]

But the actual response in the playground is:

"message": "Cannot return null for non-nullable field Movie.original_title."


Solution

  • Resolved the issue thanks to shankie_san his answer here > Apollo GraphQL "Cannot return null for non-nullable field Mutation.createUser"

    My issue was that this resolver:

      moviesFromUser: async (root, args) => {
        const movie = await prisma.movie.findMany({
          where: {userId: args.userId},
        });
        console.log(movie);
        return movie;
      },
    

    Is returning an array of movies, but my schema was returning a single movie object:

      type Query {
        moviesFromUser(userId: Int!): Movie
      }
    

    Changing moviesFromUser(userId: Int!): Movie to moviesFromUser(userId: Int!): [Movie] fixed the issue since now my schema reflects my resolver.