1

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

holler
  • 275
  • 3
  • 15
  • It looks like your resolver and function is working as you intended. It seems that your root mutation is returning a Todo object, which no longer exists. You may want to return a boolean instead. – James Teague II May 03 '19 at 00:26

1 Answers1

5

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.

Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183
  • Yes. Basically, the following code solved the problem: `const deletedTodo = await Todo.findByIdAndDelete({ _id }); return { _id: deletedTodo.id,todo: deletedTodo.todo };` Thanks for pointing me in the right direction! – holler May 03 '19 at 13:09