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 ?enter code here

subhashish negi
  • 174
  • 1
  • 9

1 Answers1

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
}
Ahmad Santarissy
  • 627
  • 6
  • 13
  • i want to achieve something like this :https://medium.com/@sarkis.tlt/how-to-use-mongoose-schema-to-generate-graphql-type-ada63a89915 product is nor graphql type so it can not be pass directly. – subhashish negi Feb 21 '19 at 10:28
  • @subhashishnegi can you share your mongoose schema? – Ahmad Santarissy Feb 21 '19 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 '19 at 05:47
  • 1
    Just to understand, you don't want your graphql schema to match mongodb schema ? – Ahmad Santarissy Feb 22 '19 at 15:46