How to dynamically access the names of fields bein

2019-08-25 20:25发布

问题:

I have two collections:

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

I resolve my author queries as follows:

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

The reason I'm resolving thus is to optimize my MongoDB requests by denormalizing my relationships. Here's the objective:

If you need just a list of authors with the titles of their works, all necessary fields are right there in dbAuthors, so no need to look up dbPosts. But if you need more details on each post returned, say, excerpts or slug, you look up dbPosts for the following condition:

{'author.id': parent.id}

But the problem is, if your query looks like this:

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

it breaks, because there's no excerpt field returned in the parent object. This problem could be easily fixed if there were some way I could determine what fields are being queried on an author's posts field and then decide if the values returned in parent would suffice. If not, I could then proceed to look up dbPosts with the author's id value. Is it possible? Because if not, it would defeat the whole purpose of denormalizing your collections, something Mongo strongly urges you to do!

回答1:

It's rather denormalized - data is duplicated ;)

You're probably looking for info.fieldNodes



标签: graphql