Search code examples
javascriptnode.jsgraphqlexpress-graphql

delete mutation returns null


I have a list of to-dos where I've successfully managed to add new items and update cache and now working on adding a delete mutation. My ultimate goal is to return an id from the delete mutation that this id could be used to update the whole list of to-dos on the client side.

I've tried passing an item's id to the mutation but it returns null.

schema

type Todo {
  _id: ID!
  todo: String!
}

type RootMutation {
  deleteTodo(_id: ID!): Todo
}

resolver

  deleteTodo: async function({ _id }, req) {
    return await Todo.deleteOne({ _id });
  }

Tested this mutation in the graphql interface at http://localhost:3000/graphql with the following code:

mutation {
  deleteTodo (_id: "example0101010101001010101aasdsadasd"){
        _id
    }
}

getting this error

{
  "errors": [
    {
      "message": "Cannot return null for non-nullable field Todo._id.",
      "locations": [
        {
          "line": 3,
          "column": 3
        }
      ],
      "path": [
        "deleteTodo",
        "_id"
      ]
    }
  ],
  "data": {
    "deleteTodo": null
  }
}

As I'm passing an item's id to the mutation it is expected to return the id of this deleted item but I keep getting null. I suspect there might be a problem with my resolver function.

Link to the github repo


Solution

  • You probably don't want to use the deleteOne method here. Looking at the type definitions for mongoose, remove, deleteOne and deleteMany do not return the deleted document. Use findByIdAndRemove instead, which will return the deleted document, or null if it wasn't found.