简体   繁体   English

通过将GraphQL作为解析参数之一传递来查询数据库

[英]GraphQL querying database by passing it as one of resolve arguments

I am interested in learning GraphQL so I can build real fullstack apps. 我对学习GraphQL感兴趣,因此可以构建真正的全栈应用程序。

I am trying to query my mongodb in my resolve function inside schema. 我正在尝试在架构内部的resolve函数中查询mongodb。 I am getting error: 我收到错误消息:

"message": "mongodb.getCollection is not a function" “ message”:“ mongodb.getCollection不是函数”

This is pretty straightforward, my mongodb argument has no getCollection function, the problem is I don't know why. 这非常简单,我的mongodb参数没有getCollection函数,问题是我不知道为什么。 I'm using mongodb, graphqlhttp, express-graphql. 我正在使用mongodb,graphqlhttp,express-graphql。

Here's my code: 这是我的代码:

In my index.js file: 在我的index.js文件中:

const graphql = express();
  graphql.use('/', graphQLHTTP(async () => ({
    graphiql: true,
    pretty: true,
    schema,
    context: {
      mongodb: await mongodb
    }
})));

In my schema file that's my resolve snippet: 在我的架构文件中,这是我的解析代码段:

resolve: async(source, { category }, { mongodb }) => {
  return await 
    stories: mongodb.getCollection('stories').find({})
  };
}

I am completly stuck at the moment, do you guys know what's wrong with my code? 我现在完全被困住了,你们知道我的代码有什么问题吗?

Try to use: 尝试使用:

  resolve: (obj, args, ctx) => {
    return mongodb.getCollection('stories').find({})
  }

needsless to say- the result from the DB should match the GraphQLObject type, something like: 不用说-数据库的结果应该与GraphQLObject类型匹配,例如:

new GraphQLList(storyType)

First of all, when you are using the .find({}) function, its generally accepted to use GraphQLList as mentioned about, because it fetches everything from the database, and I suggest you make use of your console.log(); 首先,当您使用.find({})函数时,通常会接受使用提到的GraphQLList,因为它从数据库中获取所有内容,建议您使用console.log() ;。 more often. 更多。 And from my own knowledge of graphQL, the resolve function accepts two params, the parent data and your args. 根据我对graphQL的了解,resolve函数接受两个参数,即父数据和您的args。 Check Out this tutorial link to better learn how to use GQL to query a mongodb. 请查看本教程链接,以更好地了解如何使用GQL查询mongodb。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM