0
votes

I am making a blog service using express and apollo-express along with mongodb (mongoose).

I made some mutation queries, but I have no success with obtaining the args of a mutation query.

Now I am asking for how I should structure my mutation query in order to make the thing work. thanks.

error:

"message": "Blog validation failed: title: Path title is required., slug: Path slug is required."

the query:

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

the query variables:

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

part of my graphql schema:

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
}

part of my resolvers:

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
}

part of my database schema (mongoose):

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)
1
It's a little unclear what you mean by "no success with obtaining the args of a mutation query". Are the args returning undefined inside your resolver? Please update your question to include whatever errors or unexpected behavior you are seeing.Daniel Rearden
I have updated the questionTimo Müller

1 Answers

0
votes

You've defined your newBlog mutation to accept a single argument named input. From what I can tell, you're correctly passing that argument to the mutation using a variable. Your resolver receives a map of the arguments passed to the field being resolved. That means you can access individual properties of the input object like this:

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

Note, you may want to make input non-nullable (i.e. set the type to BlogInput!), otherwise your resolver will need to handle the possibility of args.input returning undefined.