You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GraphQL Mutation类型报错,无法实现添加用户功能求解决

问题排查:GraphQL Mutation定义报错"Mutation fields must be an object..."

错误提示:"Mutation fields must be an object with field names as keys or a function which returns such an object."
尝试通过GraphQL实现添加用户功能但无法运行,以下是相关代码:

Mutation类型定义

const mutation = new GraphQLObjectType({
    name: "Mutation",
    fileds: {
        addUser: {
            type: UserType,
            args: {
                firstName: { type: new GraphQLNonNull(GraphQLString) },
                age: { type: new GraphQLNonNull(GraphQLInt) },
                companyId: { type: GraphQLString }
            },
            resolve(parentValue, { firstName, age }) {
                return axios.post("http://localhost:3000/users", { firstName, age }).then(r => r.data);
            }
        }
    }
})

UserType定义

const UserType = new GraphQLObjectType({
    name: "User",
    fields: {
        id: { type: GraphQLString },
        firstName: { type: GraphQLString },
        age: { type: GraphQLInt },
        company: {
            type: CompanyType,
            resolve(parentValue, args) {
                return axios.get("http://localhost:3000/companies/" + parentValue.companyId).then(res => res.data)
            }
        }
    }
})

解决方法

  1. 修复拼写错误:
    问题根源是Mutation定义里的属性名写错了——fileds应该改为fields(少了一个字母e)。GraphQL要求类型定义必须包含fields属性来声明字段,拼写错误导致框架无法识别合法的字段配置,因此抛出该错误。

  2. 可选优化:处理companyId参数:
    你的addUser的resolve函数目前只用到了firstName和age,但args里定义了companyId,如果需要在创建用户时一并传入该参数,需要修改resolve函数:

    resolve(parentValue, { firstName, age, companyId }) {
        return axios.post("http://localhost:3000/users", { firstName, age, companyId }).then(r => r.data);
    }
    

内容的提问来源于stack exchange,提问作者FaFa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 21:24:26