首页 > 解决方案 > 在 Mutation 中使用 GraphQL Args 属性

问题描述

我正在使用 express 和 apollo-express 以及 mongodb (mongoose) 制作博客服务。

我做了一些突变查询,但我没有成功获得突变查询的参数。

现在我在问我应该如何构建我的变异查询以使事情正常工作。谢谢。

错误:

“消息”:“博客验证失败:标题:title需要路径。,slug:slug需要路径。”

查询:

mutation ($input: BlogInput) {
  newBlog(input: $input) {
    title
    slug
  }
}

查询变量:

{
  "input": {
    "title": "ABC",
    "slug": "abc"
  }
}

我的 graphql 架构的一部分:

type Blog {
    id: ID!
    title: String!
    slug: String!
    description: String
    users: [User]!
    posts: [Post]!
}

input BlogInput {
    title: String!
    slug: String!
    description: String
}

extend type Mutation {
    newBlog(input: BlogInput): Blog
}

我的解析器的一部分:

import Blog from './blog.model'
export const blogs = async () => {
    const data = await Blog.find().exec()
    return data
}
export const newBlog = async (_, args) => {
    const data = await Blog.create({ title: args.title, slug: args.slug })
    return data
}

我的数据库架构的一部分(猫鼬):

import mongoose from 'mongoose'
const Schema = mongoose.Schema
const blogSchema = Schema({
    title: {
        type: String,
        required: true
    },
    slug: {
        type: String,
        required: true,
        unique: true
    },
    description: {
        type: String
    },
    users: {
        type: [Schema.Types.ObjectId],
        ref: 'User'
    },
    posts: {
        type: [Schema.Types.ObjectId],
        ref: 'Post'
    }
})
export default mongoose.model('Blog', blogSchema)

标签: javascriptnode.jsexpressgraphqlapollo-server

解决方案


你已经定义了你的newBlog变异来接受一个名为input. 据我所知,您正在使用变量正确地将该参数传递给突变。您的解析器接收传递给正在解析的字段的参数映射。这意味着您可以像这样访问对象的各个属性input

export const newBlog = async (_, args) => {
    const data = await Blog.create({ title: args.input.title, slug: args.input.slug })
    return data
}

请注意,您可能希望设置input不可为空(即将类型设置为BlogInput!),否则您的解析器将需要处理args.input返回未定义的可能性。


推荐阅读