首页 > 解决方案 > GraphQL 将值显示为空

问题描述

我正在学习 GraphQL,我有两种对象类型。

说,他们看起来像这样

说,书的类型是这样的

const BookType = new GraphQLObjectType({  
    name: 'Book',  
    fields: () => ({ 
        id: { type:  GraphQLID},
        name: { type: GraphQLString},
        genre: { type: GraphQLString }, 
        author: { 
            type: authorType,
            resolve(parents, args) {
               Author.findOne( 
                   {
                    name: parents.authorName
                   }, function(err, result) {
                       console.log(result)
                       return result
                   })
            }
        }

    })
})

和作者类型看起来像这样

const authorType = new GraphQLObjectType({  
    name: 'author',  
    fields: () => ({ 
        id: { type:  GraphQLID},
        name: { type: GraphQLString},
        age: { type: GraphQLInt },
        books: {  
            type: new GraphQLList(BookType), 
            resolve(parent, args) {
            }
        }
    })
})

现在,我正在通过 Mutation 添加数据(不共享它,因为我认为它无关紧要),然后运行查询graphql以在 Book Type 中添加数据。它正确显示名称、流派、id 的数据,但对于 authorType 它显示数据为空,而 console].log 结果在控制台中记录类似这样的内容

//This is console log in terminal
{ age: 'none',
  _id: 5bcaf8904b31d50a2148b60d,
  name: 'George R Martin',
  __v: 0 }

这是我在graphiql中运行的查询

mutation{
        addBooks( 
           name: "Game of Thrones",
           genre: "Science Friction", 
            authorName: "George R Martin"
            ) {
           name,
           genre,
           author {
           name
                }
              }
           }

我的整个架构都可以在这里找到

有人可以请 - 请帮我弄清楚我做错了什么?

标签: node.jsgraphql

解决方案


解析器必须返回某个值或将解析为一个值的 Promise ——如果不是,被解析的字段将返回 null。所以你的代码有两件事。第一,您既不返回值也不返回 Promise。第二,你在回调中返回一些东西,但这实际上并没有做任何事情,因为大多数库无论如何都忽略了回调函数的返回值。

您可以将回调包装在 Promise中,但这将是矫枉过正,因为 mongoose 已经提供了一种返回 Promise 的方法——只需完全省略回调即可。

resolve(parent, args) {
  return Author.findOne({name: parent.authorName)
}

您的突变解析器有效,因为您返回了调用返回的值save(),它实际上返回了一个 Promise,它将解析为正在保存的模型实例的值。


推荐阅读