Express GraphQL创建球队并关联球员ID的填充问题求助
问题分析与解决方案
你遇到的球员信息无法正确填充的问题,核心有三个错误点:
1. GraphQL类型定义不匹配
TeamType中的players字段被定义为单个UserType,但你的MongoDB模型里players是数组类型,这会导致GraphQL无法正确解析数组数据,最终返回null。
2. Resolve函数的异步处理错误
map循环中没有返回User.findById的查询结果,导致最终返回的是undefined数组parent.players存储的是MongoDB的ObjectId(或字符串形式的ID),不是包含id属性的对象,所以player.id是无效的查询条件- 多个
findById是异步操作,需要用Promise.all等待所有查询完成
3. 可选优化:创建球队后直接关联填充球员数据
创建球队时仅保存ID,后续查询需要手动关联,也可以在保存后直接调用populate获取完整球员数据。
修正后的代码
1. 修正TeamType的players字段
const TeamType = new GraphQLObjectType({ name: "Team", fields: () => ({ id: { type: GraphQLID }, teamName: { type: GraphQLString }, teamNumber: { type: GraphQLInt }, inMatchIDs: { type: new GraphQLList(MatchType) }, players: { // 改为数组类型,匹配MongoDB模型 type: new GraphQLList(UserType), // 用async/await + Promise.all处理异步查询 async resolve(parent, args) { return Promise.all(parent.players.map(playerId => User.findById(playerId))); }, }, }), });
2. 优化createTeam的Mutation Resolve(可选)
如果希望创建球队后直接返回完整的球员数据,可以在保存后调用populate:
createTeam: { type: TeamType, args: { teamName: { type: GraphQLString }, players: { type: GraphQLList(GraphQLID) }, }, async resolve(parent, args) { const team = new Team({ teamName: args.teamName, players: args.players, }); // 保存后填充players字段 const savedTeam = await team.save(); return savedTeam.populate('players'); }, },
验证效果
修正后执行你的GraphQL请求,应该会返回正确的球员name信息:
{ "data": { "createTeam": { "teamName": "champions", "id": "xxx", "teamNumber": null, "players": [ { "name": "xxx" }, { "name": "xxx" } ] } } }
注:teamNumber返回null是因为创建球队时没有传入该参数,属于正常现象。
内容的提问来源于stack exchange,提问作者cordovez
相关产品推荐
相关产品推荐

