简体   繁体   English

使用express和graphql查询mongodb

[英]query mongodb with express and graphql

how do we use graph ql with mongo db here is my code with resolvers 我们如何使用图形ql与mongo db这里是我的代码与解析器

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 我正在使用字符串转换我的响应,在模式中我们如何为它提供Product模式的类型?在此处输入代码

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. 你的getproducts应该返回一个与你的GraphQL Schema的属性相匹配的对象,我需要更多的代码来正确回答你的问题,但这里是你的问题的快速解决方案,请记住mongodb Product schema应该与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 GraphQL架构

type Product {
   test: String
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM