I'm new to GraphQL. I've got a schema and mutation for adding data, but I'm a bit stuck on how to make an update mutation to update existing data on the database.
I think I know what I might need to do to achieve this, but I'd appreciate some pointers on whether or not my idea is the right approach or not.
Here's my schema which contains my mutation GraphQLObject.
const graphql = require("graphql");
const _ = require("lodash");
const Student = require("../models/students");
const Class = require("../models/classes");
const classes = require("../models/classes");
const {
GraphQLObjectType,
GraphQLString,
GraphQLSchema,
GraphQLID,
GraphQLInt,
GraphQLList,
GraphQLNonNull,
} = graphql;
const Mutation = new GraphQLObjectType({
name: "Mutation",
fields: {
addStudent: {
type: StudentType,
args: {
name: { type: new GraphQLNonNull(GraphQLString) },
age: { type: new GraphQLNonNull(GraphQLString) },
test1: { type: new GraphQLNonNull(GraphQLString) },
classId: { type: new GraphQLNonNull(GraphQLID) },
},
resolve(parent, args) {
let student = new Student({
name: args.name,
age: args.age,
test1: args.test1,
classId: args.classId,
});
console.log(student);
return student.save();
},
},
addClass: {
type: ClassType,
args: {
name: { type: new GraphQLNonNull(GraphQLString) },
year: { type: new GraphQLNonNull(GraphQLString) },
},
resolve(parent, args) {
let newclass = new Class({
name: args.name,
year: args.year,
});
return newclass.save();
},
},
editStudent: {
type: StudentType,
args: {
id: { type: new GraphQLNonNull(GraphQLID)},
name: { type: GraphQLString },
age: { type: GraphQLString },
test1: { type: GraphQLString },
classId: { type: GraphQLID },
},
resolve(parent, args) {
//logic that finds the relevant data object by id, then updates that object//
}
}
}
},
});
module.exports = new GraphQLSchema({
query: RootQuery,
mutation: Mutation,
});
Would I be correct in saying that inside the resolve function I need to first find the relevant object in the database by id and then return the args of whatever arg has been updated/changed? I'm not really sure how to find an object by id on MongoDB though.
Any pointers would definitely be appreciated.