如何在graphql中获取mongodb结果

时间:2019-08-15 05:52:54

标签: mongodb graphql

const axios = require('axios');
const mongodb = require('mongodb');

const MongoClient = mongodb.MongoClient;
const url = "mongodb://localhost:27017/graphql";

const {
GraphQLObjectType,
GraphQLInt,
GraphQLString,
GraphQLBoolean,
GraphQLList,
GraphQLSchema
} = require('graphql');

// Launch Type
const LaunchType = new GraphQLObjectType({
name: 'Launch',
fields: () => ({
    name: { type: GraphQLString },
})
});

// Root Query
const RootQuery = new GraphQLObjectType({
    name: 'RootQueryType',
    fields: {
        launches: {
        type: new GraphQLList(LaunchType),
            resolve(parent, args) {
                return MongoClient.connect(url, (err, client) => {
                    client.db('graphql').collection('users').find()
                });
            }
        },
    }
});
module.exports = new GraphQLSchema({
query: RootQuery
});

在这里我试图连接graphql-express-mongodb

但是我认为我的RootQuery出现了一些问题,res出现错误。

我是新手,不知道如何获取数据并返回

请帮助我正确连接。请看看。

2 个答案:

答案 0 :(得分:0)

在这里您如何连接express-graphql

const express = require('express');
const expressGraphQL = require('express-graphql');
const schema = require('./schema');

const app = express();


app.use(
   '/graphql',
   expressGraphQL({
     schema,
     graphiql: true
    })
);

您将解决方案中的连接恢复为

 resolve(parent, args) {
         MongoClient.connect(url, (err, client) => {
             return  client.db('graphql').collection('users').find()
         });
 }

答案 1 :(得分:0)

您可以返回从解析器返回值的promise。就您而言,您要返回一个回调函数,而不要返回内部诺言。

此外,您还在此处连接到解析程序中的数据库,因此您将在每次请求到API时从数据库连接/断开连接,这不是一个好习惯。最好只连接一次并重用连接

const client = await MongoClient.connect(url)
// Root Query
const RootQuery = new GraphQLObjectType({
    name: 'RootQueryType',
    fields: {
        launches: {
        type: new GraphQLList(LaunchType),
            resolve(parent, args) {
                return client.db('graphql').collection('users').find()
                });
            }
        },
    }
});
module.exports = new GraphQLSchema({
query: RootQuery
});