首页 > 解决方案 > 用于解析评论数组的字段解析器

问题描述

我有一个包含评论数组的帖子模型。我正在尝试使用字段解析器返回可以在我的 graphql 游乐场中查询的评论列表。我能够成功解决帖子用户但是,我无法解决帖子评论。有人可以帮我吗?谢谢

  Query: {
    //todo Using GraphQL Field Resolvers
    getPosts: combineResolvers(isAuthenticated, async (_, __, { Post }) => {
      const posts = await Post.find({});

      return posts;
    }),
  },
  Post: {
     comments: async (parent, input, { Comment }) => {
       console.log("parent", parent, input);
     },
    user: async (parent, __, { User }) => {
      try {
        const user = await User.findById(parent.user);
        return user;
      } catch (error) {
        console.log(error);
        throw error;
      }
    },
  },

标签: mongoosegraphql

解决方案


以下方法可以工作。如果有人有更好的建议,欢迎分享。希望这个答案能够帮助某人。谢谢

  Post: {
    comments: async (parent, __, { Post, Comment }) => {
      console.log("parent", parent);
      return parent.comments.map(async (c) => {
        return Comment.findById(c);
      });
    },
    user: async (parent, __, { User }) => {
      try {
        const user = await User.findById(parent.user);
        return user;
      } catch (error) {
        console.log(error);
        throw error;
      }
    },
  },
  Comment: {
    user: async (parent, __, { User }) => {
      console.log("parent ", parent);
      const user = await User.findById(parent.user);
      return user;
    },
  },


推荐阅读