为什么 strapi 的 `find()` 不查询 return 数组?
Why doesn't strapi's `find()` query return an array?
上下文
我有一个前端应用程序,它需要来自 API 的博客数组 post,当您使用 GET 请求调用 http://strapi-url/posts/
时,它 returns 所有结果作为数组中的对象。 快乐的日子。
问题
最终我想要更复杂的带有查询参数的 GET 选项,所以我需要修改 post 控制器并为 find()
.
编写一个自定义函数
当我修改 api/post/controllers/post.js
中的 find()
函数,并使其 return 成为 strapi.query('post').find()
的结果时,它 return 是一个对象键而不是数组。
代码
async find(ctx) {
let entity = await.strapi.query('post').find();
return sanitizeEntity(entity, { model: strapi.models.post });
},
我知道我可以在前端将它简单地转换成一个数组,但感觉这是一个混乱的解决方案,我宁愿理解为什么它不会return 一个数组,什么是解决问题的最佳方法。
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);
}
您可以通过制作自己的 自定义清理函数 来解决它,其中 returns 一个数组,或者在返回之前处理结果,如下所示:
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
上下文
我有一个前端应用程序,它需要来自 API 的博客数组 post,当您使用 GET 请求调用 http://strapi-url/posts/
时,它 returns 所有结果作为数组中的对象。 快乐的日子。
问题
最终我想要更复杂的带有查询参数的 GET 选项,所以我需要修改 post 控制器并为 find()
.
当我修改 api/post/controllers/post.js
中的 find()
函数,并使其 return 成为 strapi.query('post').find()
的结果时,它 return 是一个对象键而不是数组。
代码
async find(ctx) {
let entity = await.strapi.query('post').find();
return sanitizeEntity(entity, { model: strapi.models.post });
},
我知道我可以在前端将它简单地转换成一个数组,但感觉这是一个混乱的解决方案,我宁愿理解为什么它不会return 一个数组,什么是解决问题的最佳方法。
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);
}
您可以通过制作自己的 自定义清理函数 来解决它,其中 returns 一个数组,或者在返回之前处理结果,如下所示:
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