Search code examples
graphql-jsexpress-graphql

GraphQLError Schema validation while triggering a mutation


I am trying my hand at GraphQL and I seem to have run into a strange error.

Here is my mutation

    const createNewTask = {
        name: "AddATask",
        description: "A mutation using which you can add a task to the todo list",
        type: taskType,
        args: {
            taskName: {
                type: new gql.GraphQLNonNull(gql.GraphQLString)
            },
            authorId: {
                type: new gql.GraphQLNonNull(gql.GraphQLString)
            }
        },
        async resolve(_, params) {
            try {
                const task = newTask(params.taskName);
                return await task.save();
            } catch (err) {
                throw new Error(err);
            }
        }
    };

Task type is as defined as follows

const taskType = new gql.GraphQLObjectType({
    name: "task",
    description: "GraphQL type for the Task object",
    fields: () => {
        return {
            id: {
                type: gql.GraphQLNonNull(gql.GraphQLID)
            },
            taskName: {
                type: gql.GraphQLNonNull(gql.GraphQLString)
            },
            taskDone: {
                type: gql.GraphQLNonNull(gql.GraphQLBoolean)
            },
            authorId: {
                type: gql.GraphQLNonNull(gql.GraphQLString)
            }
        }
    }
});

I am trying to add a task using the graphiql playground.

mutation {
  addTask(taskName: "Get something", authorId: "5cb8c2371ada735a84ec8403") {
    id
    taskName
    taskDone
    authorId
  }
}

When I make this query I get the following error

"ValidationError: authorId: Path `authorId` is required."

But when I remove the authorId field from the mutation code and send over a mutation without the authorId in it, I get this error

"Unknown argument \"authorId\" on field \"addTask\" of type \"Mutation\"."

So this proves that the authorId is available is in the request. I debugged the same on vscode and can see the value. I can't seem to figure out what is wrong.


Solution

  • I figured out what the error was. The erro was actually caused by my mongoose schema and not by graphql schema.

    const taskSchema = new Schema(
        {
            taskName: {
                type: String,
                required: true
            },
            taskDone: {
                type: Boolean,
                required: true
            },
            authorId: {
                type: mongoose.Types.ObjectId,
                required: true
            }
        },
        {
            collection: "tasks"
        }
    );
    

    But what is wierd is that the final error message has no indication that it was the mongoose schema validation failure. And the error states that it is a graphql error hence the confusion. Hope it helps someone.