javascript - 为什么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 });
},
我知道我可以简单地将它转换为前端的数组,但感觉像是一个凌乱的解决方案,我宁愿理解为什么它不返回数组,以及处理解决方案的最佳方法是什么。
解决方案
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
推荐阅读
- reactjs - 在页面中嵌入外部表单
- spring-boot - 有没有办法在 application.properties 文件中不使用 spring.batch.job.enabled: false 来禁用 Spring 批处理作业自动启动
- git - 推送到多个 FTP 服务器
- shell - 获取 bash_profile 时,Ansible 使用来自 shell 模块的别名
- python-3.x - [::-1] 实际上在 numpy 中做了什么?
- r - 将标记 (S3:data.frame) 转换为具有水平的因子
- openxml - 这个 OpenXml 转换元素使用什么单位?
- flutter - 如何为单个页面上的两个 ListView 动态分配屏幕空间?
- c++ - 如何通过 Rcpp 更改函数输入参数名称?希望 R 函数输入名称包含“点”
- java - 每次按下按钮时数据都会翻倍