我是 GraphQL 的新手。我有一个用于添加数据的模式和突变,但我有点坚持如何进行更新突变以更新数据库上的现有数据。
我想我知道我可能需要做些什么来实现这一目标,但我会很感激一些关于我的想法是否是正确方法的指示。
这是我的架构,其中包含我的变异 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,
});
我是否正确地说在解析函数中我需要首先通过 id 在数据库中找到相关对象,然后返回已更新/更改的任何 arg 的 args?不过,我不确定如何在 MongoDB 上通过 id 查找对象。
任何指针肯定会受到赞赏。