I need to check whether the data exists/already exists or not in the database. I am using graphql and mongoose.
Here's my graphql mutation object:
addBook: {
type: BookType,
args: {
name: { type: new GraphQLNonNull(GraphQLString) },
genre: { type: new GraphQLNonNull(GraphQLString) },
authorid: { type: new GraphQLNonNull(GraphQLString) }
},
resolve(parent, args){
let book = new Book({
name: args.name,
genre: args.genre,
authorid: args.authorid
});
return book.save();
}
},
updateBook: {
type: BookType,
args: {
name: { type: new GraphQLNonNull(GraphQLString) },
updateName: { type: new GraphQLNonNull(GraphQLString) }
},
resolve(parent, args){
let book = Book.findOneAndUpdate({name: args.name}, {name: args.updateName}, {new: true});
return book.exec();
}
},
deleteBook: {
type: BookType,
args: {
name: { type: new GraphQLNonNull(GraphQLString) }
},
resolve(parent, args){
let book = Book.findOneAndDelete({name: args.name});
return book.exec();
}
}
All of these successfully add, update, and delete in the MongoDB database. But I don't know how to validate it first if the data does exist or not. When I try to run an update on a non-existing book, GraphiQL UI throws null
{
"data": {
"updateBook": null
}
}
How can I check for this? Thank you!