Node.js中Apollo Server的GraphQL嵌套查询问题求助
解决Apollo Server嵌套查询"Cannot return null for non-nullable field Comment.commentId."错误
你的错误由两个核心问题导致,逐个修复即可:
问题1:评论数据类型不匹配
你定义的Comment类型中commentId是非空Int类型(Int!),但测试数据里第三条评论的commentId是字符串"3",GraphQL无法将字符串转为合法Int,会返回null,触发非空校验错误。
问题2:Product的comment字段解析器逻辑完全错误
产品数据数组products里根本没有comment属性,你在解析器里调用parent.comment.map会直接拿到undefined,而且你的逻辑返回的是布尔值(parent.productId === commentList.productId),不是评论对象,完全不符合[Comment]的类型要求。
修复步骤及完整代码
1. 修正评论数据类型
把第三条评论的commentId从字符串"3"改为数字3:
let comments = [ { commentId : 1, commentBody : "amazing product really cheap flights", productId : 101, }, { commentId : 2, commentBody : "amazing product really cheap flights", productId : 102, }, { commentId : 3, // 从字符串改为数字 commentBody : "amazing product really cheap flights", productId : 103, }, ]
2. 修正Product的comment解析器逻辑
解析器需要从全局comments数组中筛选出与当前产品productId匹配的评论:
const resolvers = { Query: { productCount: () => products.length, allProducts: () => products, allComments: () => comments, findProduct: (root, args) => products.find(p => p.productTitle === args.productTitle), }, Product: { comment: parent => { // 筛选与当前产品ID匹配的评论 return comments.filter(comment => comment.productId === parent.productId) } } }
3. 可选优化:语义化字段名
建议把Product类型里的comment改成comments(因为是数组),更符合语义:
type Product { productId: ID!, productTitle: String!, product_Description: String!, price: String! comments: [Comment] // 字段名改为复数形式 }
对应的查询也需要同步修改:
query { allProducts { product_Description comments { // 同步改为复数字段名 commentBody } } }
修改后重新启动服务器,执行查询就能正常返回产品关联的评论了。
内容的提问来源于stack exchange,提问作者user2286483
相关产品推荐
相关产品推荐

