如何在GraphQL中定义嵌套Schema并解决查询根类型报错问题
错误原因
报错核心是GraphQL规范强制要求必须定义**根查询类型Query**作为所有查询请求的统一入口,你当前的Schema仅定义了Student、Location两个业务类型,没有声明对外可查询的根字段,因此无法识别请求的查询入口。
正确实现方法
1. 补充Schema中的根查询定义
在buildSchema的入参中新增Query类型,将所有需要对外暴露的查询字段都声明在该类型下:
- 你需要直接查询的
address字段 - 嵌套查询场景下的
student字段(可选,用于演示嵌套Schema效果)
2. 匹配根解析器结构
root对象的第一层字段需要和Query类型中声明的字段完全对应,嵌套字段的解析规则会自动匹配子类型的结构。
完整可运行代码
var express = require('express'); var { graphqlHTTP } = require('express-graphql'); var { buildSchema } = require('graphql'); var schema = buildSchema(` type Student { sid: ID, name: String, subjects: [String!], address: Location } type Location{ unit: String, city: String, country: String, postCode: Int } # 新增必须的根查询类型 type Query { address: Location student(sid: ID!): Student } `); var root = { // 对应Query中的address字段 address: () => ({ city: 'London', country: 'UK', postCode: 12345 }), // 对应Query中的student字段,演示嵌套查询 student: (args) => ({ sid: args.sid, name: '张三', subjects: ['数学', '英语'], address: { city: '北京', country: '中国' } }) }; var app = express(); app.use('/graphql', graphqlHTTP({ schema: schema, rootValue: root, graphiql: true, })); app.listen(4000); console.log('Running a GraphQL API server at http://localhost:4000/graphql');
测试验证
服务启动后访问http://localhost:4000/graphql,执行你原来的查询语句即可得到正确结果:
{ address { city } }
返回示例:
{ "data": { "address": { "city": "London" } } }
如果需要测试嵌套Schema效果,可执行以下查询:
{ student(sid: "1001") { name subjects address { city country } } }
内容的提问来源于stack exchange,提问作者Chong Lip Phang
相关产品推荐
相关产品推荐

