【发布时间】:2021-07-21 15:10:03
【问题描述】:
我是 Strapi 和 Mongoose 的新手,所以如果这是一个愚蠢的问题,我深表歉意。
按照文档 (https://strapi.io/documentation/developer-docs/latest/development/backend-customization.html),我正在尝试在 Strapi 中创建一个自定义查询,我想在其中返回按名称 desc 排序的名为 people 的整个集合。但是当我点击端点时,我得到一个 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" });,错误仍然存在,所以我认为我在控制器中使用服务的方式可能有问题?
【问题讨论】:
-
不执行
toObject是否还会出现错误? -
@AlexanderStaroselsky 是的,它仍然存在。在我看来,我在控制器或查询中使用服务的方式有问题,但我无法弄清楚它是什么
标签: javascript node.js mongoose strapi