【问题标题】:How to make a GraphQL update mutation?如何进行 GraphQL 更新突变?
【发布时间】:2021-12-02 16:32:23
【问题描述】:

我是 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 查找对象。

任何指针都将不胜感激。

【问题讨论】:

    标签: graphql apollo-server graphiql graphql-mutation


    【解决方案1】:

    找到了我要找的东西。

    editStudent: {
          type: StudentType,
          args: {
            id: { type: new GraphQLNonNull(GraphQLID)},
            name: { type: GraphQLString },
            age: { type: GraphQLString },
            test1: { type: GraphQLString },
            classId: { type: GraphQLID },
          },
          resolve(parent, args) {
            return Student.findOneAndUpdate({_id: args.id}, { test1: args.test1, name: args.name}, { new: true})
          }
    

    【讨论】:

      猜你喜欢
      • 2018-07-04
      • 2022-01-10
      • 2016-05-30
      • 2020-05-30
      • 2019-05-24
      • 2021-02-17
      • 2018-09-03
      • 2023-01-14
      • 1970-01-01
      相关资源
      最近更新 更多