如何使用GraphQL查询与ObjectID相关的嵌套文档

时间:2019-03-05 19:47:40

标签: node.js mongodb mongoose graphql

USER有一个字段“ groups”,它是与GROUP对应的objectID的数组 GROUP具有字段“ boards”,该字段是与BOARD对应的objectID的数组 BOARD具有字段“ posts”,该字段是与POST对应的objectID的数组 POST的字段“ comment”是与COMMENT相对应的objectID数组

我的目标是能够像这样查询GrapQL:

Query{
  user('_id'){
    username  
    groups{
       name
       boards{
         name
         posts{
           comment{
             text
           }    
         }
        }
     }
   }
}

因此,仅通过提供带有用户ID的查询,我就可以获得与用户相关的所有组,论坛,帖子和评论。

我的类型定义如下:

type Query {
            user(_id: String): User
            groups(_id: String): [Group]
            boards(_id: String): [Board]
            posts(_id: String): [Post]
            comments(_id: String): [Comment]
        }

        type User {
            _id: String,
            username: String,
            email: String,
            Groups: [Group]
        }

        type Group {
            _id: String,
            name: String,
            bio: String,
            owner: User
            members: [User]
            boards: [Board]
        }

        type Board {
            _id: String,
            name: String,
            bio: String,
            group: Group
            posts: [Post]
        }

        type Post {
            _id: String,
            name: String,
            board: Board,
            comments: [Comment]
        }

        type Comment {
            _id: String
            text: String
        }

        schema {
            query: Query
        }

我的解析器(我确定问题出在哪里):

const resolvers = {
    Query: {
        user: async (root, { _id }) => {
            return prepare(await Users.findOne(ObjectId(_id)))
        },
        groups: async (root, { _id }) => {
            return prepare(await Groups.findOne(ObjectId(_id)))
        },
        boards: async (root, { _id }) => {
            return prepare(await Boards.findOne(ObjectId(_id)))
        },
        posts: async (root, { _id }) => {
            return prepare(await Posts.findOne(ObjectId(_id)))
        },
        comments: async (root, { _id }) => {
            return prepare(await Coments.findOne(ObjectId(_id)))
        }
    },
    User: {
        groups: async ({_id}) => {
          return (await Groups.find({_id: _id}).toArray()).map(prepare)
        }
      }
}

基本上,我试图通过一个调用来处理一个大型的,嵌套的查询。所有模型都由objectID关联。是否有人对如何进行此处有任何意见,或者是否有相关文档的链接?我搜索了所有内容,但似乎找不到与此相关的文档。通过objectID查询相关文档。

0 个答案:

没有答案