【问题标题】:How to dynamically access the names of fields being queries in a GraphQL resolver?如何在 GraphQL 解析器中动态访问正在查询的字段名称?
【发布时间】:2019-02-23 09:43:21
【问题描述】:

我有两个收藏:

dbPosts

id: mongoose.Schema.Types.ObjectId,
title: { type: String },
content: { type: String },
excerpt: { type: String },
slug: { type: String },
author: {
   id: { type: String },
   fname: { type: String },
   lname: { type: String },
}

dbAuthors

id: mongoose.Schema.Types.ObjectId,
fname: { type: String },
lname: { type: String },
posts: [
         id: { type: String },
         title: { type: String }
       ]

我按如下方式解决我的作者查询:

Query: {
    authors: (parent, root, args, context) => {
      return dbAuthor.find({});
    },
    author: (root, args, context) => {
      return dbAuthor.findById(args.id);
    },
  },

  Author: {
    posts: (parent) => {
      if(parent.posts) {
        return parent.posts;
      } else {
        return dbAuthor.find({'author.id': parent.id});
      }
    },
  }

我这样解决的原因是通过非规范化我的关系来优化我的 MongoDB 请求。这是目标:

如果您只需要包含作品标题的作者列表,所有必要的字段都在 dbAuthors 中,因此无需查找 dbPosts。但是,如果您需要有关返回的每个帖子的更多详细信息,例如摘录或 slug,您可以查找 dbPosts 以了解以下情况:

{'author.id': parent.id}

但问题是,如果您的查询如下所示:

authors(id: "3") {
  fname
  lname
  posts {
    title
    excerpt
  }
}

它会中断,因为父对象中没有返回 excerpt 字段。如果有某种方法我可以确定在作者的帖子字段上查询哪些字段,然后确定在 parent 中返回的值是否足够,则可以轻松解决此问题。如果没有,我可以继续使用作者的 id 值查找 dbPosts。可能吗?因为如果不是这样,它将破坏非规范化集合的整个目的,Mongo 强烈敦促您这样做!

【问题讨论】:

    标签: graphql


    【解决方案1】:

    这是相当非规范化的——数据是重复的;)

    您可能正在寻找info.fieldNodes

    【讨论】:

      猜你喜欢
      • 2021-11-17
      • 2019-04-06
      • 2020-05-22
      • 2019-08-16
      • 1970-01-01
      • 2018-11-25
      • 2022-12-14
      • 2021-02-01
      • 2019-09-10
      相关资源
      最近更新 更多