【发布时间】:2019-10-25 04:44:29
【问题描述】:
您好,我是 graphql 的新手,我想知道是否可以在我的架构中创建一个根查询,该查询将返回一个数组或列表作为结果。
更准确地说,我在架构中创建了以下类型:
const ResourceType = new GraphQLObjectType({
name:'Resource',
fields:()=>({
id: {type: GraphQLID},
url: {type: GraphQLString},
title: {type: GraphQLString},
author: {type: GraphQLString},
license:{type: GraphQLString},
LicenseScore: {type: GraphQLFloat},
})
});
我想查询数据库中的所有资源,以便获得它们的许可证类型,然后根据许可证分配分数。是否可以有一个查询来获取每个资源的许可证并返回如下数组:[[id:1209,score:3.5],[1203,4.5]....]?
我创建了一个将分数更新到数据库的突变,这里是:
updateAllLicenses: {
type: new GraphQLList(ResourceType),
async resolve(parent,args){
var licns;
var scr;
await Resource.find({}).then(async function(results){
var num = results.length;
var scr=0;
for (var i=0; i<num; i++){
if (! (results[i].license in licenseScores)){
scr = 0;
}
else{
scr = licenseScores[results[i].license];
}
await Resource.findByIdAndUpdate(results[i].id{LicenseScore:scr});
}
});
return await Resource.find({});
}
}
但是我想知道是否有一种方法可以直接从查询中获取这些分数,而不是将它们保存在数据库中。我尝试将类型更改为 new GraphQLList(GraphQLFloat) 并返回一个包含 scr 值的数组,但我在 graphql api 中收到一个错误,说我的突变中有错误的输出类型。
【问题讨论】:
-
你确定你想要的结果的语法:` [[id:1209,score:3.5],[1203,4.5]....]?
? Or should you meant[[id:1209 ,score:3.5],[id:1203,score:4.5]....]?` -
不,我的意思是 [[1209,3.5],[1203,4.5]] 我只写了 id 和 score 来显示我希望保存值的顺序。是否可以从查询中获取数组?如果是,返回值应该是什么类型?
标签: mongodb graphql-js