How to fetch mongodb result in graphql

后端 未结 2 970
误落风尘
误落风尘 2020-12-12 07:06
const axios = require(\'axios\');
const mongodb = require(\'mongodb\');

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


        
相关标签:
2条回答
  • 2020-12-12 07:44

    here how you connect 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
        })
    );
    

    you return the connection in the resolve correct it to

     resolve(parent, args) {
             MongoClient.connect(url, (err, client) => {
                 return  client.db('graphql').collection('users').find()
             });
     }
    
    0 讨论(0)
  • 2020-12-12 08:04

    You can return promises that return the value from the resolver. In your case you're returning a callback function and you're not returning the inner promise.

    Also here you're connecting to the database in your resolver so you will be connecting/disconnecting from the database on every request to your API which is not a good practice. its better to connect once and reuse the connection

    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
    });
    
    0 讨论(0)
提交回复
热议问题