假设我们使用这个请求查询服务器,我们只想获得以下用户的电子邮件,我当前的实现要求整个用户对象从MongoDB,我可以想象这是极其低效的。
GQL
{
user(id:"34567345637456") {
email
}
}如何创建只返回这些指定字段的MongoDB筛选器?例如,
JS object
{
"email": 1
}我的当前服务器正在运行Node.js、Fastify和Mercurius。
发布于 2022-01-30 15:46:44
扩展了@Manuel Spigolon最初的答案,他说他的实现的一个缺陷是它不能处理嵌套的查询和“多个查询到一个请求”,这个实现试图修复这个请求。
function formFilter(context:any) {
let filter:any = {};
let getValues = (selection:any, parentObj?:string[]) => {
//selection = labelSelection(selection);
selection.map((selection:any) => {
// Check if the parentObj is defined
if(parentObj)
// Merge the two objects
_.merge(filter, [...parentObj, null].reduceRight((obj, next) => {
if(next === null) return ({[selection.name?.value]: 1});
return ({[next]: obj});
}, {}));
// Check for a nested selection set
if(selection.selectionSet?.selections !== undefined){
// If the selection has a selection set, then we need to recurse
if(!parentObj) getValues(selection.selectionSet?.selections, [selection.name.value]);
// If the selection is nested
else getValues(selection.selectionSet?.selections, [...parentObj, selection.name.value]);
}
});
}
// Start the recursive function
getValues(context.operation.selectionSet.selections);
return filter;
}输入
{
role(id: "61f1ccc79623d445bd2f677f") {
name
users {
user_name
_id
permissions {
roles
}
}
permissions
}
}输出(JSON.stringify)
{
"role":{
"name":1,
"users":{
"user_name":1,
"_id":1,
"permissions":{
"roles":1
}
},
"permissions":1
}
}https://stackoverflow.com/questions/70906149
复制相似问题