在 apostrophe-headless 中过滤自定义字段

Filtering on custom fields in apostrophe-headless

我正在使用带有撇号无头的撇号。我有一个名为 bundles 的撇号模块,我想根据自定义字段对其进行过滤。文档说我需要定义一个 apostrophe-pieces-pages 模块才能启用它。

这是我的配置:

  'bundles': {
    extend: 'apostrophe-pieces',
    name: 'bundles',
    restApi: {
      maxPerPage: 10,
    }
  },

  'bundles-pages': {
    extend: 'apostrophe-pieces-pages',
    piecesFilters: [
      {
        name: 'name'
      },
      {
        name: 'slug'
      }
    ]
  },

如果我进行全文搜索:

/api/v1/bundles?page=1&search=text 

它按预期工作,但如果我尝试过滤 slug:

/api/v1/bundles?page=1&slug=slug_value 

它 returns 所有捆绑包而不是匹配的捆绑包。

apostrophe-pieces-pages 不需要使游标筛选方法可用于 API 和其他代码。我认为混淆来自文档关注 apostrophe-pieces-pages 的事实,因为直接渲染整页是 Apostrophe 教程主要系列关注的用例。

在您的帮助下,我们更新了 apostrophe-headless 以支持一个选项来指定应以相同方式为 public API 标记 "safe" 的过滤器apostrophe-pieces-pages 做到了:

'my-module': {
  restApi: {
    // We're assuming here that you have added fields
    // called 'color' and 'brand' in your schema
    safeFilters: [ 'slug', 'color', 'brand' ]
  }
}

但是,对于任何热衷于查询 slug 属性 的人来说,请记住,如果您正在拨打 API 电话,您可能最好通过他们的 _id,使用记录的 REST 模式:

/api/v1/bundles/IDGOESHERE

与 _id 不同,Slug 会偶尔更改。如果您知道 _id 而不是创建 user-facing "friendly URL" 那么您应该使用 _id.

我 运行 遇到了同样的问题,发现解决方案是添加自定义过滤器,如下所述:https://apostrophecms.org/docs/tutorials/intermediate/cursors.html#custom-filters

我对 link 中显示的示例代码所做的唯一更改是在以 self.and({...然后 return 仍然是包含所有文档的初始游标,但实际上你不需要它 return 什么。所以,而不是 :

self.and({ marketId: market._id });

我这样做了(有点老套,但你明白了):

self.and({ marketId: market === undefined ? 9999999999 : market._id });