我对Strapi和Mongoose都是新手,所以如果这是一个愚蠢的问题,我很抱歉。
在文档(https://strapi.io/documentation/developer-docs/latest/development/backend-customization.html)之后,我尝试在Strapi中创建一个自定义查询,在该查询中,我希望返回名为people的整个集合,该集合按名称desc排序。但是当我到达端点时,我得到了一个500错误,检查终端时,错误消息是CastError: Cast to ObjectId failed for value "alldesc" at path "_id" for model "people"。
下面是我的代码:
services/people.js
module.exports = {
findByNameDesc() {
const result = strapi
.query("people")
.model.find()
.sort({ name: "descending" });
return result.map((entry) => entry.toObject());
},
};controllers/people.js
module.exports = {
async alldesc(ctx) {
const entities = await strapi.services.people.findByNameDesc(ctx);
return entities.map((entity) =>
sanitizeEntity(entity, { model: strapi.models.people })
);
},
};config/routes.json
{
"routes": [
...
{
"method": "GET",
"path": "/people/alldesc",
"handler": "people.alldesc",
"config": {
"policies": []
}
}
]
}我做错了什么?
更新:即使从查询中删除.sort({ name: "descending" });,错误仍然存在,所以我在想,可能是我在控制器中使用服务的方式有问题?
发布于 2021-07-22 16:18:28
问题出在routes.json上。基本上,Strapi似乎不喜欢斜杠/,所以我没有使用/people/alldesc,而是尝试了/people-alldesc,并且它起作用了。
在服务中也不需要return result.map((entry) => entry.toObject());,这会导致另一个错误,只需执行return result工作即可。
https://stackoverflow.com/questions/68472052
复制相似问题