【问题标题】:Fetch deep nested documents with GraphQL使用 GraphQL 获取深层嵌套文档
【发布时间】:2016-07-20 03:37:27
【问题描述】:

只有在被要求时才使用 graphql 获取深层嵌套对象的最佳方法是什么。 我说的是性能方面

假设您有以下 mongo/mongoose 架构:

User 
  |
  |_ Name
  |
  |_ Friends (RefId into User)
      |
      |_ User
          |
          |_ Friends (RefId into User)

      .....

假设每个用户有很多朋友,而这些朋友又会有很多其他朋友, 如何决定在 resolve 函数中需要多深的 populate

“只是填充”的幼稚方法可能是有害的,因为许多查询可能只是选择了位于 0 级别的字段 name,但最终会填充 1/2 的数据库。

提前致谢。

【问题讨论】:

  • 为什么不只返回在父用户的好友字段中找到的用户?您是否特别想将朋友的朋友热切地加载到特定的深度?如果是这样,您需要警惕已经是其他朋友的朋友的朋友的朋友,这样您就不会陷入无限循环。
  • @BrendanTurner 我在这里试图说明的重点不是“循环循环”,而是我们如何动态决定我们应该填充多深。如果它可以帮助您将示例与拥有有工作领域的朋友。现在有些查询需要填充 3-rd level nesting ,但有些只需要获取名称。
  • 对,所以在查询中指定。这是一个应该有助于澄清的要点:gist.github.com/xpepermint/7376b8c67caa926e19d2

标签: mongodb mongoose graphql flask-graphql


【解决方案1】:

最好的方法是让 GraphQL 客户端指定它想要的嵌套数据的深度,即让客户端在请求用户的朋友时传递一个参数。

使用graphql npm 包,实现如下:

const UserType = new GraphQLObjectType({
  name: 'NestedUser',
  fields: {
    ...
    ...
    friends: {
      type: new GraphQLList(UserType),
      args: {
        level: {
          type: GraphQLInt,
          defaultValue: 0,
        },
        ...connectionArgs,
      },
      resolve: (user, {level, ...args}) => {
        // Populate nestedFriends according to the level
        return nestedFriends;
      },
    },
  },
});

【讨论】:

  • 这很有趣,谢谢。我想知道我们是否可以在不明确提及深度的情况下根据字段操作 mongo 查询
猜你喜欢
  • 1970-01-01
  • 2023-03-07
  • 2018-10-13
  • 2015-07-30
  • 1970-01-01
  • 2016-01-12
  • 1970-01-01
  • 1970-01-01
  • 2016-04-16
相关资源
最近更新 更多