【发布时间】:2020-09-22 17:47:57
【问题描述】:
我正在尝试使用 GraphQL 查询单个 MongoDB 文档 (trivia),但其中一个文档字段出现问题。 trivia.rounds 字段应该返回一个对象数组(LightningRound 或 MultipleChoiceRound)。
schema.graphql
type Trivia {
_id: String!
createdAt: String!
rounds: [Round]!
}
interface Round {
type: String!
theme: String!
pointValue: Int!
}
type LightningRound implements Round {
type: String!
theme: String!
pointValue: Int!
questions: [LightningRoundQuestion]
}
type MultipleChoiceRound implements Round {
type: String!
theme: String!
pointValue: Int!
questions: [MultipleChoiceRoundQuestion]
}
// ...
trivia.js // resolver
require('dotenv').config()
const { ObjectId } = require('mongodb')
const trivia = (app) => {
return async (root, { _id }) => {
return app
.get('db')
.collection(process.env.DB_COLLECTION_TRIVIA)
.findOne(ObjectId(_id))
}
}
module.exports = {
trivia
}
graphql query
query {
trivia(_id: "5e827a4e1c9d4400009fea32") {
_id
createdAt
rounds {
__typename
... on MultipleChoiceRound {
type
theme
}
... on PictureRound {
type
theme
}
... on LightningRound {
type
theme
}
}
}
}
我不断收到错误:
"message": "Abstract type \"Round\" must resolve to an Object type at runtime for field \"Trivia.rounds\" with value { questions: [[Object], [Object]] }, received \"undefined\". Either the \"Round\" type should provide a \"resolveType\" function or each possible type should provide an \"isTypeOf\" function."
我不明白resolveType 或isTypeOf 是什么意思。我在其他问题中看到了这一点,但不知道在我的设置中实现什么。如果我删除 rounds 字段,数据库连接和解析器工作正常,所以它就在那里......
【问题讨论】:
-
trivia的解析器返回一个对象(来自 db),但它不包含rounds属性......并且没有解析器为此返回值(对象数组) -
@xadm 从
trivia返回的对象确实有rounds数组,其中包含轮数。 -
@xadm 感谢您的提示。我来到这个全新的领域,试图围绕 GraphQL。我尝试了工会的东西,并没有奏效。我只是不知道该怎么做。哦,好吧。
标签: node.js mongodb express graphql