【问题标题】:GraphQL Expected Iterable, but did not find one for field while using findGraphQL 期望 Iterable,但在使用 find 时没有找到一个字段
【发布时间】:2018-09-06 15:24:32
【问题描述】:

目前我正在使用 Apollo/GraphQL/Node.js/Sequelize 构建我的后端服务器,我的服务器代码如下所示,在那里我可以使用 req.user 获取当前登录用户

app.use(
  '/graphql',
  bodyParser.json(),
  graphqlExpress(req => ({
    schema,
    context: {
      models,
      user: req.user,
    },
  })),
);

现在我有两个模型User和Recipe,并且关联规则是Recipe属于User,所以在Recipe schema中我可以使用UserId知道是哪个用户创建了这个schema,Recipe schema是

type Recipe {
  id: Int!
  authorName: String!
  authorFbPage: String @virtual
  perfumeName: String!
  message: String
  UserId: Int
}

type Query {
  allRecipe: [Recipe]
  meRecipe: [Recipe]
  AvailableWatchRecipe: [Recipe]
}

我的问题在 meRecipe 部分,这个查询应该能够显示登录用户创建的食谱,解析器代码是

meRecipe: async (parent, args, { models, user }) => {
      if (user) {
        console.log(user.id);
        console.log(user.username);
        return models.Recipe.find({ where: { UserId: user.id } })
          .then((result) => { return result });
      }

      return null;
    }, 

你可以看到我也使用console.log来检查我是否可以得到当前用户信息,它实际上可以,所以我真的很困惑为什么我在GraphQL服务器中运行这个Query时总是显示"message": "Expected Iterable, but did not find one for field Query.meRecipe . 我检查了这些资源: https://github.com/brysgo/graphql-bookshelf/issues/10GraphQL Expected Iterable, but did not find one for field xxx.yyy 但是没有一个适合我的情况,谁能给我一些建议,谢谢!

【问题讨论】:

    标签: node.js sequelize.js graphql apollo


    【解决方案1】:

    而不是使用:

    models.Recipe.find
    

    使用

    models.Recipe.findAll // this will return single result in array
    

    【讨论】:

    • 嗨,它成功了!非常感谢,但是为什么 find 不能做 findAll 做的事情呢?
    • @yamahachou , find 将返回单个对象,因此不可迭代,您可以使用 findAll 来获得它,即使返回单个结果,它也会始终返回结果数组。
    猜你喜欢
    • 2021-01-20
    • 2020-07-04
    • 2021-09-14
    • 2019-08-01
    • 2019-03-05
    • 2018-06-25
    • 2022-11-11
    相关资源
    最近更新 更多