【问题标题】:How can I return the data from multiple collections from Graphql?如何从 Graphql 返回多个集合中的数据?
【发布时间】:2016-08-31 01:23:11
【问题描述】:

如何从 Graphql 返回多个集合中的数据?

const jobsCollection = db.collection('jobs');

const companysCollection = db.collection('company');


import {
  GraphQLList,
  GraphQLObjectType,
  GraphQLSchema,
  GraphQLString,
  GraphQLInt,
  GraphQLFloat,
  GraphQLEnumType,
  GraphQLNonNull
} from 'graphql';


const Company = new GraphQLObjectType({
  name: 'Company Name',
  description: 'test',
  fields: () => ({
    _id: {type: GraphQLString},
    name: {type: GraphQLString},
    address : {type: GraphQLString}
  }

  })
});

通过下面的查询,我也想查询公司集合。我该怎么做?

const Job = new GraphQLObjectType({
  name: 'job',
  description: 'test',
  fields: () => ({
    _id: {type: GraphQLString},
    name: {type: GraphQLString},
    skill_set : {type: GraphQLString},
    company: {type: Company}
  }

  })
});

## 通过下面的查询我也想查询公司集合。我怎样才能做到这一点? ##

const Query = new GraphQLObjectType({
  name: "Queries",
  fields: {
    jobs: {
      type: new GraphQLList(Job),
      resolve: function(rootValue, args, info) {
        let fields = {};
        let fieldASTs = info.fieldASTs;
        fieldASTs[0].selectionSet.selections.map(function(selection) {
          fields[selection.name.value] = 1;
        });
        return jobsCollection.find({}, fields).toArray();
      }
    }
  }
});

【问题讨论】:

    标签: graphql graphql-js


    【解决方案1】:

    GraphQL 中的模式和查询并不关心您的数据是在一个、两个还是十个集合中。您甚至可以在许多不同的服务器、不同的数据库中拥有数据。 GraphQL 服务器通过遵循您在架构中定义的关系进行连接(即在您的案例中组合来自不同集合的数据),然后为响应中的每个字段运行所谓的解析函数以获取实际数据。

    所以您的查询将如下所示:

    query {
      jobs {
        _id
        company {
          name
        }
      }
    }
    

    您已经有一个解决工作的功能,现在您只需为公司定义另一个功能。大概您的工作集合在其文档中包含公司(和名称),或者包含公司的 _id,因此您在公司解析功能中所要做的就是这样:

    resolve(job, args, context, info){
      return companyCollection.findOne({ _id: job.companyId });
    }
    

    我写了一篇较长的中篇文章,更详细地解释了 GraphQL 的执行。你可以找到它here

    【讨论】:

    • resolve(job, args, context, info){ return companyCollection.findOne({ _id: job.companyId });这里你还没有使用rootValue作为resolve函数中的参数。什么是rootValue???
    • 我刚刚将rootValue变量重命名为job,就是这样。我在答案末尾发布的链接解释了根值的来源。
    猜你喜欢
    • 1970-01-01
    • 2021-10-07
    • 2019-06-08
    • 1970-01-01
    • 2018-06-06
    • 1970-01-01
    • 2019-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多