【问题标题】:How do I add custom queries in GraphQL using Strapi?如何使用 Strapi 在 GraphQL 中添加自定义查询?
【发布时间】:2020-08-25 04:43:59
【问题描述】:

我正在使用 graphQL 在 React 中查询 MongoDB 数据库,并使用 Strapi 作为我的 CMS。我正在使用 Apollo 来处理 GraphQL 查询。我可以通过传递 ID 参数来获取我的对象,但我希望能够传递不同的参数,例如名称。

这行得通:

{
  course(id: "5eb4821d20c80654609a2e0c") {            
    name
    description
    modules {
       title
    } 
  }
}

这不起作用,在类型为 \"Query\" 的字段 \"course\" 上给出错误 "Unknown argument \"name\"

{
  course(name: "course1") {            
    name
    description
    modules {
       title
    } 
  }
}

根据我的阅读,我需要定义一个自定义查询,但我不确定如何执行此操作。

Course 的模型目前是这样的:

  "kind": "collectionType",
  "collectionName": "courses",
  "info": {
    "name": "Course"
  },
  "options": {
    "increments": true,
    "timestamps": true
  },
  "attributes": {
    "name": {
      "type": "string",
      "unique": true
    },
    "description": {
      "type": "richtext"
    },
    "banner": {
      "collection": "file",
      "via": "related",
      "allowedTypes": [
        "images",
        "files",
        "videos"
      ],
      "plugin": "upload",
      "required": false
    },
    "published": {
      "type": "date"
    },
    "modules": {
      "collection": "module"
    },
    "title": {
      "type": "string"
    }
  }
}

和 任何帮助将不胜感激。

【问题讨论】:

  • 后端堆栈?服务器/lib/lang/任何东西?
  • 使用 GraphQL 和 Apollo 来查询连接到 MongoDB 数据库的 Strapi CMS,用 React 编写?

标签: mongodb graphql strapi


【解决方案1】:

参考 Strapi GraphQL Query API

您可以使用 where 和查询 courses 来过滤您的字段。您将获得课程列表而不是一门课程

这应该可行:

{
  courses(where: { name: "course1" }) {
    name
    description
    modules {
       title
    } 
  }
}

【讨论】:

  • 我试过这个,但不幸的是我在“查询”类型的字段“课程”上得到“未知参数”。” - 我认为这是因为架构中定义的查询只接受 ID,但我不确定如何为 Name 添加查询
  • 应该是courses,我已经修改了答案。对于将来的查询,您可以查阅我在回答中引用的文档。
猜你喜欢
  • 2018-06-04
  • 1970-01-01
  • 1970-01-01
  • 2020-07-04
  • 2016-06-16
  • 2022-11-04
  • 2020-12-19
  • 2020-01-29
  • 2019-06-12
相关资源
最近更新 更多