如何在GraphQL中处理嵌套数据 筛选指定国家作者的全部书籍
代码调整步骤
1. 调整RootQuery的books字段配置
给books查询增加country入参,同时修改resolve逻辑实现关联筛选,修改后完整代码如下:
// 首先确保你已经导入了GraphQLString,你的文件顶部应该有类似如下导入代码 const { GraphQLObjectType, GraphQLID, GraphQLString, GraphQLList } = require('graphql'); const BookType = new GraphQLObjectType({ name: "Book", fields: () => ({ id: { type: GraphQLID }, name: { type: GraphQLString }, genre: { type: GraphQLString }, author: { type: AuthorType, resolve(parent, args) { return Author.findById(parent.authorId); }, }, }), }); const RootQuery = new GraphQLObjectType({ name: "RootQueryType", fields: { books: { type: new GraphQLList(BookType), // 新增国家筛选参数 args: { country: { type: GraphQLString } }, async resolve(parent, args) { // 没有传国家参数时返回全部书籍 if (!args.country) { return Book.find({}); } // 第一步:查询所有属于指定国家的作者ID列表 const matchedAuthors = await Author.find({ country: args.country }, { _id: 1 }); const authorIds = matchedAuthors.map(author => author._id); // 第二步:查询所有关联了这些作者ID的书籍 return Book.find({ authorId: { $in: authorIds } }); // 如果你熟悉MongoDB聚合,也可以用以下写法一次完成查询,性能更高 // return Book.aggregate([ // { // $lookup: { // from: "authors", // 替换为你的作者集合实际名称,通常是复数小写 // localField: "authorId", // foreignField: "_id", // as: "author" // } // }, // { $unwind: "$author" }, // { $match: { "author.country": args.country } } // ]) }, }, }, });
2. 查询使用示例
需要查询孟加拉国作者的书籍时,直接传入country参数即可,查询语句如下:
query { books(country: "Bangladesh") { name genre author { name country } } }
查询返回结果就会过滤掉非指定国家作者的书籍,符合你需要的筛选效果。
内容的提问来源于stack exchange,提问作者soykot2910
相关产品推荐
相关产品推荐

