【问题标题】:Why doesn't strapi's `find()` query return an array?为什么strapi的`find()`查询不返回一个数组?
【发布时间】:2020-11-03 06:44:09
【问题描述】:

上下文

我有一个前端应用程序,它需要来自 API 的一系列博客文章,当您使用 GET 请求调用 http://strapi-url/posts/ 时,它会将所有结果作为数组中的对象返回。 快乐的日子。

问题

最终我希望有更复杂的 GET 选项和查询参数,所以我需要修改后控制器并为 find() 编写一个自定义函数。

当我修改 api/post/controllers/post.js 中的 find() 函数,并让它返回 strapi.query('post').find() 的结果时,它返回一个带有键的对象而不是一个数组。

代码

 async find(ctx) {
    let entity = await.strapi.query('post').find();
    return sanitizeEntity(entity, { model: strapi.models.post });
  },

我知道我可以简单地将它转换为前端的数组,但感觉像一个凌乱的解决方案,我宁愿理解为什么它不返回一个数组,以及会是什么解决问题的最佳方法。

【问题讨论】:

  • 它返回多少组对象?如果它返回多个对象,那么它是一个正在返回的数组。
  • 不,正如我所提到的,它是一个带有键的对象,即 { 0: { data: 1 }, 1: { data: 2} }

标签: javascript koa strapi


【解决方案1】:

sanitizeEntity 中的代码实际上是这样做的。您可以在源代码中查看它(node_modules/strapi-utils/lib/sanitize-entity.js)。您还可以通过删除 sanitizeEntity 行来查看这一点 - 您将从 await.strapi.query('post').find() 获得一个数组。

您可以运行以下测试 (add a custom endpoint) 来查看结果:

  async test2(ctx) {
    let entity = await strapi.query('post').find();
    ctx.send({
      message: 'okay',
      posts: entity,
      sanitizedPosts: sanitizeEntity(entity, { model: strapi.models.post })
    }, 200);
  }

您可以通过创建自己的自定义清理函数来解决它,该函数返回一个数组,或者在返回之前处理结果,如下所示:

let entity = await strapi.query('post').find();
let sanitizedEntity = sanitizeEntity(entity, { model: strapi.models.post });
//process sanitized results to an array 
//return the result as array

【讨论】:

    猜你喜欢
    • 2012-05-04
    • 1970-01-01
    • 2018-05-22
    • 1970-01-01
    • 1970-01-01
    • 2021-09-02
    • 2021-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多