Node.js – Apollo GraphQL “Cannot return null for non-nullable field Mutation.createUser”

apollo-servergraphqlnode.jssequelize.js

I know this is a somewhat common issue, but my implementation differs from the other posts. I'm using the most basic implementation which I can't get to work. I'm using Sequelize with MySQL as the database implementation.

resolvers.js

const resolvers = {
    Query: {
        async getStudent (root, { id }, { models }) {
            return models.User.findByPk(id)
        },
    },
    Mutation: {
        async createUser (root, { name, email }, { models }) {
            return models.User.create({
                name,
                email
            })
        },
    },
}

schema.js

const { gql } = require('apollo-server-express');
const typeDefs = gql`
    type User {
        id: Int!
        name: String!
        email: String!
    }
    type Query {
        getUser(id: Int!): User
        getAllUsers: [User!]!
    }
    type Mutation {
        createUser(name: String!, email: String!): User!
    }`
module.exports = typeDefs;

User model

'use strict';
module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    name: DataTypes.STRING,
    email: DataTypes.STRING
  }, {});
  User.associate = function(models) {
    // associations can be defined here
  };
  return User;
};

Yet when running the following mutation:

mutation{ createUser(name:"Nate", email:"nate@test.com"){
id } }

I receive:

"errors": [
{
"message": "Cannot return null for non-nullable field Mutation.createUser.",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"createUser"
],

Best Answer

In my case it was because the createUser call was not asynchronous. Hopefully this helps someone:

return await models.User.create({
    name,
    email
})
Related Topic