query mongodb with express and graphql

query mongodb with express and graphql


3

how do we use graph ql with mongo db here is my code with resolvers

var resolvers = {
    test:()=>{
        return getproducts()
    },
 }

 const getproducts=()=>{
    return new Promise((resolve,reject)=>{
        Product.find({}).exec()
        .then(resp=>{
            console.log("response is ",resp);
            let stringData = resp.toString()
            resolve(stringData);
        }).catch(err=>{
            console.log('error is ',err);
            reject(err);
        })
    })
 }

and schema is :

test:String!

i am converting my response in string , in schema how can we give it the type of Product schema ?

1 Answer
1


1

Your getproducts should return an object matching the properties of your GraphQL Schema, I would need more code to answer your question properly but here’s a quick fix for your issue, keeping in mind that that mongodb Product schema should match the GraphQL Schema.

var resolvers = {
    Query: {
       getProducts: () => {
          return getproducts();
       },
    },
 }

 const getproducts = () => {
    return new Promise((resolve,reject)=>{
        Product.find({}).exec()
        .then(resp=>{
            console.log("response is ",resp);
            // let stringData = resp.toString()
            resolve(resp);
        }).catch(err=>{
            console.log('error is ',err);
            reject(err);
        })
    })
 }

GraphQL Schema

type Product {
   test: String
}

type Query {
   getProducts: [Product] // Query returns an array of products
}

4

  • i want to achieve something like this :medium.com/@sarkis.tlt/… product is nor graphql type so it can not be pass directly.

    – subhashish negi

    Feb 21, 2019 at 10:28

  • @subhashishnegi can you share your mongoose schema?

    – Ahmad Santarissy

    Feb 21, 2019 at 14:40

  • const mongoose = require('mongoose'); const productSchema = mongoose.Schema({ _id: mongoose.Schema.Types.ObjectId, name:{type:String, required:true}, price:{type:Number, required:true} }) module.exports = mongoose.model('Product', productSchema)

    – subhashish negi

    Feb 22, 2019 at 5:47


  • 1

    Just to understand, you don't want your graphql schema to match mongodb schema ?

    – Ahmad Santarissy

    Feb 22, 2019 at 15:46



Leave a Reply

Your email address will not be published. Required fields are marked *