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
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 negiFeb 21, 2019 at 10:28
-
@subhashishnegi can you share your mongoose schema?
– Ahmad SantarissyFeb 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 negiFeb 22, 2019 at 5:47
-
1
Just to understand, you don't want your graphql schema to match mongodb schema ?
– Ahmad SantarissyFeb 22, 2019 at 15:46