1
votes

So I want a user to be able to edit his data (in this case the email)in graphql, but i get a "Cannot return null for non-nullable field Mutation.updateUser" error and i cant figure out whats wrong

my defs:

    type Mutation{
        updateUser(id: ID!  email: String!): User!
    }
type User{
        id: ID!
        email: String!
        token: String!
        createdAt: String!
        username: String!
        bio: String,
    

    }

code:

module.exports = {
    Mutation: {
      async updateUser(parent, args) {
        return User.findOneAndUpdate({ id: args.id }, { email: args.email }, { new: true })
      }
    }
}

user schema:

const userSchema = new Schema({
    username: String,
    password: String,
    email: String,
    createdAt: String,
    bio: String,
    
});
2
You have declared that the mutation will return a non-null User object all times, but your resolver is most prolly returning null. Either mark it is as nullable or update User.findOneAndUpdate() to not return null. - Mat G

2 Answers

0
votes

Define your schema like this. Suppose you need to make bio field nullable = true simply make it required = false. It will solve your problem.

 const userSchema = new Schema({
    username:  {type: String, required: true},
    password:  {type: String, required: true},
    email:  {type: String, required: true},
    bio:  {type: String, required: false},
}, {timestamps: true});

Moreover, for better code practice, use {timestamps: true} in your schema it will automatically generate your createdAt, updatedAT column You have no need to explicitly define these columns. These columns will be generated and updated automatically.

0
votes

You can update the schema so that the mutation can return null without throwing errors.

type Mutation{
    updateUser(id: ID!, email: String!): User
}