我试图通过在Team(Parent)中添加玩家名称并努力尝试获取玩家名称列表来实现嵌套变异......
Inside GraphiQL工具(localhost:4000 / graphiql),这是我添加的Add Mutation变量......
mutation AddPlayerToTeam($name: String!, $teamId: ID!){
addPlayerToTeam(player: $name, teamId: $teamId){
id
players{
name
}
}
}
查询变量,添加teamID和名称......
{
"teamId": "5aff545371fc930a4c43b2b9",
"name": "John Doe"
}
结果显示......
{
"data": {
"addPlayerToTeam": {
"id": "5b072774e385740c38483111",
"players": []
}
}
}
但我期待球员名字能够像这样出现......
{
"data": {
"addPlayerToTeam": {
"id": "5b072774e385740c38483111",
"players": [
{
"name": "John Doe"
}
]
}
}
}
突变代码......
AddPlayerToTeam: {
type: TeamType,
args: {
name: { type: new GraphQLNonNull(GraphQLString) },
teamId: { type: new GraphQLNonNull(GraphQLID) }
},
resolve(parent, { name, teamId }) {
let addPlayer = new Player({ name, teamId });
return addPlayer.save();
}
},
我很难找到为什么我会收到"players": []
而不是"players": [ {"name": "John Doe" } ]
的原因。
我需要在.then(...)
之后加入.save()
才能获得结果吗?任何例子?感谢您的帮助。
BTW,我使用的是mongoDB / mongoose方法。将它们保存在本地mongoDB中。
答案 0 :(得分:0)
为此找到解决方案...感谢graphql.slack中的#andrewingram提供帮助。只需包含.then(...)
即可返回结果。
AddPlayerToTeam: {
type: TeamType,
args: {
name: { type: new GraphQLNonNull(GraphQLString) },
teamId: { type: new GraphQLNonNull(GraphQLID) }
},
async resolve(parent, { name, teamId }) {
let addPlayer = new Player({ name, teamId });
await addPlayer.save();
return Team.findById(teamId);
}
},
或承诺版
resolve(parent, { name, teamId }) {
let addPlayer = new Player({ name, teamId });
return addPlayer.save().then(() => Team.findById(teamId));
}
希望有所帮助。