首页 > 解决方案 > 为什么strapi的`find()`查询不返回一个数组?

问题描述

语境

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

问题

最终我希望有更复杂的带有查询参数的 GET 选项,所以我需要修改 post 控制器并为find().

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

代码

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

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

标签: javascriptkoastrapi

解决方案


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

您可以运行以下测试(添加自定义端点)来查看结果:

  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

推荐阅读