【问题标题】:Create custom query in Strapi with Mongoose使用 Mongoose 在 Strapi 中创建自定义查询
【发布时间】: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


【解决方案1】:

问题出在routes.json。基本上似乎 Strapi 不喜欢斜线 / 所以我尝试了 /people/alldesc 而不是 /people-alldesc 并且它有效。

在服务中也不需要return result.map((entry) => entry.toObject());,这会导致花药错误,只需执行return result就可以了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-25
    • 2022-08-22
    • 1970-01-01
    • 1970-01-01
    • 2017-05-14
    • 2018-06-04
    • 1970-01-01
    • 2017-08-15
    相关资源
    最近更新 更多