node.js - 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
}
}
}
有人可以请 - 请帮我弄清楚我做错了什么?
解决方案
解析器必须返回某个值或将解析为一个值的 Promise ——如果不是,被解析的字段将返回 null。所以你的代码有两件事。第一,您既不返回值也不返回 Promise。第二,你在回调中返回一些东西,但这实际上并没有做任何事情,因为大多数库无论如何都忽略了回调函数的返回值。
您可以将回调包装在 Promise中,但这将是矫枉过正,因为 mongoose 已经提供了一种返回 Promise 的方法——只需完全省略回调即可。
resolve(parent, args) {
return Author.findOne({name: parent.authorName)
}
您的突变解析器有效,因为您返回了调用返回的值save()
,它实际上返回了一个 Promise,它将解析为正在保存的模型实例的值。
推荐阅读
- rest - Jax rs 休息客户端 - 超时配置
- javascript - Slice into chunks and average (reduce) array in JS
- ios - 我可以在情节提要中使 ViewController 处于非活动状态吗?
- angular - Angular 4 获取使用 *ngIf 隐藏的元素的高度
- python-3.x - 安装后无法在 PyCharm (Jupyter) 中导入 Xgboost 包
- python - 如何在熊猫中创建叠加条图
- html - 垂直对齐两个按钮
- php - 使用 DomXPath 从 $p->nodeValue 获取 HTML 注释?
- javascript - 通过 React.js 中的 API 调用返回名称
- php - 使用 PHP 中的复选框更新 SQL 数据库中的单个行的问题