如何在GraphQL解析器中动态访问作为查询的字段的名称?

如何在GraphQL解析器中动态访问作为查询的字段的名称?,graphql,Graphql,我有两个收藏: 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 }, } i

我有两个收藏:

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 },
}
id: mongoose.Schema.Types.ObjectId,
fname: { type: String },
lname: { type: String },
posts: [
         id: { type: String },
         title: { type: String }
       ]
dbAuthors

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 },
}
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
  }
}

它会中断,因为父对象中没有返回
extract
字段。如果有某种方法可以确定在作者的posts字段上查询哪些字段,然后确定parent中返回的值是否足够,那么这个问题很容易解决。如果没有,我就可以继续用作者的id值查找dbPosts。可能吗?因为如果不这样做,它将破坏您的收藏非规范化的全部目的,Mongo强烈敦促您这样做

它相当非规范化-数据重复;)

你可能在找