我刚开始学习 GraphQL,做了一个简单的例子。我有这个架构
const {
GraphQLObjectType,
GraphQLString,
GraphQLSchema,
GraphQLID,
// GraphQLInt,
GraphQLList,
GraphQLNonNull
} = graphql;
const ContinentType = new GraphQLObjectType({
name: 'Continent',
fields: () => ({
id: {
type: GraphQLID
},
details: {
type: GraphQLString
},
name: {
type: GraphQLString
},
country_to_show: {
type: CountryType,
resolve(parent, args) {
console.log(parent);
console.log(parent.countryID);
return Country.findById(parent.countryID);
}
}
})
});
const CountryType = new GraphQLObjectType({
name: 'Country',
fields: () => ({
id: {
type: GraphQLID
},
name: {
type: GraphQLString
},
flag: {
type: GraphQLString
},
countryCode: {
type: GraphQLString
},
details: {
type: GraphQLString
}
})
});
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
continent: {
type: ContinentType,
args: {
id: {
type: GraphQLID
}
},
resolve(parent, args) {
return Continent.findById(args.id);
}
},
country: {
type: CountryType,
args: {
id: {
type: GraphQLID
}
},
resolve(parent, args) {
return Country.findById(args.id);
}
},
countrys: {
type: new GraphQLList(CountryType),
resolve(parent, args) {
return Country.find({});
}
},
contintens: {
type: new GraphQLList(ContinentType),
resolve(parent, args) {
return Continent.find({});
}
},
}
});
const Mutation = new GraphQLObjectType({
name: 'Mutation',
fields: {
addContinent: {
type: ContinentType,
args: {
name: {
type: new GraphQLNonNull(GraphQLString)
},
details: {
type: new GraphQLNonNull(GraphQLString)
},
countryID: {
type: new GraphQLNonNull(GraphQLList(GraphQLString))
}
},
resolve(parent, args) {
let continent = new Continent({
name: args.name,
details: args.details,
countryID: args.countryID
});
return continent.save();
}
},
addCountry: {
type: CountryType,
args: {
name: {
type: new GraphQLNonNull(GraphQLString)
},
details: {
type: new GraphQLNonNull(GraphQLString)
},
flag: {
type: new GraphQLNonNull(GraphQLString)
},
countryCode: {
type: new GraphQLNonNull(GraphQLString)
},
},
resolve(parent, args) {
let country = new Country({
name: args.name,
details: args.details,
countryCode: args.countryCode,
flag: args.flag
});
return country.save();
}
}
}
});
module.exports = new GraphQLSchema({
query: RootQuery,
mutation: Mutation
});
当我尝试添加新大陆时,我可以在数据库中看到记录已存储
{
"_id": {
"$oid": "5b60dea3ff0eba10ada3cbff"
},
"countryID": [
"5b5cd39951017b08d3e1303a",
"5b5cd3c77640c708edbcbf45"
],
"name": "something",
"details": "something",
"__v": 0
}
但是在 GrapiQL 中执行 addContinent 突变时
mutation{
addContinent(name:"something",details:"something",countryID:["5b5cd39951017b08d3e1303a","5b5cd3c77640c708edbcbf45"]){
name
country_to_show{
name
}
}
}
我看不到嵌套的嵌套结果,country_to_show
我在结果查询中只得到一个国家名称,而不是我保存的两个,不明白为什么?
{
"data": {
"addContinent": {
"name": "something",
"country_to_show": {
"name": "albania"
}
}
}
}
我相信这与country_to_show
在 ContinentType 中搜索数据库中的单个国家/地区这一事实有关,但即使在运行我得到的突变时尝试在结果查询中返回国家/地区列表时,我也无法确定解决方案null
。