【问题标题】:Field Resolver to resolve array of Comments用于解析评论数组的字段解析器
【发布时间】:2020-08-25 23:44:36
【问题描述】:

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

  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;
      }
    },
  },

【问题讨论】:

    标签: mongoose graphql


    【解决方案1】:

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

      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;
        },
      },
    
    

    【讨论】:

      猜你喜欢
      • 2012-05-31
      • 1970-01-01
      • 2013-07-31
      • 2020-06-30
      • 2019-05-01
      • 2011-08-08
      • 2018-07-22
      • 2019-02-15
      • 2012-07-12
      相关资源
      最近更新 更多