mongoose Graphql:在对象数组上构造查询时出现问题

kr98yfug  于 2023-03-12  发布在  Go
关注(0)|答案(1)|浏览(107)

这是我存储在MongoDB中的数据:

{
   "experience":{
      "pastProjects":[
         {
            "1":[
               {
                  "title":"One"
               }
            ]
         },
         {
            "2":[
               {
                  "title:":"TWO"
               }
            ]
         }
      ]
   }
}

这是我的 Mongoose 模式。

const pastProjectsSchema =  new mongoose.Schema({
    experience: {
        pastProjects:[
            { 
                1: [
                    { 
                        title: String
                    }
                ]
            }
        ]
    }
        
})

这是我的typeDefs中的Graphql查询。

export const typeDefs = gql`
    type Query {
        experiences:[Experience]
    }
    type Experience{
        experience: String
    }

`;

我确信它不是一个字符串,我只是不知道如何构造gql来匹配mongoose.Schema。

wz3gfoph

wz3gfoph1#

]解算的溶液[
我花了一些时间来重组JSON,它在MongoDB中看起来是这样的。

{
    "pastprojects": [{
            "title": "One Title",
            "main": "- Blah Line 1<br>- Blah Line 2",
            "sub": "Sub One Description"

        },
        {
            "title": "Two Title",
            "main": "- Blah Line 1<br>- Blah Line 2",
            "sub": "Sub Two Description"

        }

    ]
}

这是我的mongoose.模型在文件Book.js:

import mongoose from "mongoose";
const pastProjectsSchema =  new mongoose.Schema({
        pastprojects:[
                {   
                    title: String,
                    main: String,
                    sub: String
                }
            ]
            
    })
    
    export const Experience = mongoose.model( "Experience", pastProjectsSchema , "pastprojects");

This is my GraphQl typeDefs.js:

        import gql from 'graphql-tag';   
    export const typeDefs = gql`
        type Query {
            experiences: [Experience]
        }
        type Experience {
            pastprojects: [ProjectDetail]
          }
        
          type ProjectDetail {
            title: String
            main: String
            sub: String
          }
           
    `;

这是我的resolver.js:

import { Experience} from './models/Book.js'

export const resolvers = {
    Query: {
        experiences: async() => await Experience.find({}),
    }
};

感谢Cankat Saracc帮助我完成gql结构。

相关问题