3

StackOverflow!

One day ago I've started to learn a new thing for me - GraphQL. Now I know how to add and read objects from a database using GraphQL. I have tried to find an answer to question "how to remove an object from database". But it's no luck. Can you help me with this "hard" (for you) question?

Thanks for your answers!

oles
  • 166
  • 1
  • 2
  • 10

3 Answers3

3

I found it! Maybe someone needs the answer.

Use Model.findByIdAndDelete(id, options, callback);

My code:

deleteImage: {
  type: ImageType,
  args: {
    id: { type: GraphQLID }
  },
  resolve(parent, args) {
    return Image.findByIdAndDelete(args.id);
  }
}

It works!

oles
  • 166
  • 1
  • 2
  • 10
1

This might be another way to tackle this problem. I'm using Graphql to build a live chat app and I was trying to give the user the power to delete their messages when I came across this solution.

let messages = []

My definitions:
type Query {
    messages: [Message!]
}
type Mutation {
    deleteMessage(id:String!):String
}

My resolvers:
Query: {
    messages: () => messages,
  }
Mutation: {
    deleteMessage: (parent, {id}) => {
     let ID = parseInt(id)
     messages = messages.filter((message) => message.id !== ID);
     return id;
}
}

I query the messages and put them in the array named messages and then when the user wants to delete the message from the frontend the action send the id of the message to the server and then I use the filter method above to remove the specified message.

RyanK
  • 21
  • 4
0

TypeDefs:

  type Mutation {
    deleteUser(id: ID!): User
  }

resolvers:

deleteUser: (parent, args, context, info) => {
  const id = args.id;
  _.remove(UserList, (user) => user.id === +id);
  return null;
},
Haroon Hayat
  • 329
  • 2
  • 4