【问题标题】:CastError with GET endpoint but not with POST endpoint in Express / Mongoose?CastError 与 GET 端点但不是与 Express / Mongoose 中的 POST 端点?
【发布时间】:2021-07-28 06:54:20
【问题描述】:

我正在测试一个端点,它使用 mongoose 查询从 id 获取用户数据。我的代码像 POST 端点一样工作,但如果端点更改为 GET,则会返回一个奇怪的错误。

router.route("/test").get(async (req, res) => { // works for POST route and request, not GET
  const ids = req.body.ids;
  users = [];
  for (let i = 0; i < ids.length; i++) {
    const userData = await User.findById(ids[i]);
    users.push(userData);
  }
  res.json(users);
});

使用上面的代码,我收到此错误:“错误:CastError: Cast to ObjectId failed for value “test” at path “_id” for model “Group””

用 POST 替换请求类型,我得到了我想要的结果。为什么会这样,其余的代码都一样?

【问题讨论】:

  • 请显示您发出的两个 HTTP 请求(GET 和 POST)

标签: node.js mongodb express mongoose


【解决方案1】:

不要让端点有点相似
例子:

product/:id

and similar with

item/:id

让您的端点独一无二

product/:id_product

item/:id_item

核心是,检查您的端点并使其独一无二!
上面的例子是我遇到的一个案例

【讨论】:

    猜你喜欢
    • 2019-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多