首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从MongoDB请求构造GraphQL查询

从MongoDB请求构造GraphQL查询
EN

Stack Overflow用户
提问于 2022-01-29 13:57:07
回答 1查看 393关注 0票数 1

假设我们使用这个请求查询服务器,我们只想获得以下用户的电子邮件,我当前的实现要求整个用户对象从MongoDB,我可以想象这是极其低效的。

代码语言:javascript
复制
GQL
{
  user(id:"34567345637456") {
    email
  }
}

如何创建只返回这些指定字段的MongoDB筛选器?例如,

代码语言:javascript
复制
JS object
{
   "email": 1
}

我的当前服务器正在运行Node.js、Fastify和Mercurius。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-30 15:46:44

扩展了@Manuel Spigolon最初的答案,他说他的实现的一个缺陷是它不能处理嵌套的查询和“多个查询到一个请求”,这个实现试图修复这个请求。

代码语言:javascript
复制
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;
}

输入

代码语言:javascript
复制
{
  role(id: "61f1ccc79623d445bd2f677f") {
        name
    users {
      user_name
      _id
      permissions {
        roles
      }
    }
    permissions
  }
}

输出(JSON.stringify)

代码语言:javascript
复制
{
   "role":{
      "name":1,
      "users":{
         "user_name":1,
         "_id":1,
         "permissions":{
            "roles":1
         }
      },
      "permissions":1
   }
}
票数 -2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70906149

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档