【问题标题】:Mongoose CastErrorMongoose CastError
【发布时间】:2018-09-19 12:57:33
【问题描述】:

我有以下代码,它完全没有任何作用,并且由于某些原因,我对 mongoose 有一个错误,它甚至没有被调用,这是代码:

.post('/testRequest', express.json(), upload.none(), async (req, res) => {
    try {
      res.status(200);
      res.send('test');
    } catch (err) {
      console.error(err.stack);
      res.status(err.code || 400);
      res.send(err.message || err);
    }
  })

这是错误:

message: 'Cast to ObjectId failed for value "test" at path "_id" for model "Requests"',
name: 'CastError',
stringValue: '"test"',
kind: 'ObjectId',
value: 'test',
path: '_id',
reason: undefined,

我尝试了很多东西,但似乎没有解决它

【问题讨论】:

  • 可以参考这个解决方案stackoverflow.com/questions/34985332/…
  • 你在这段代码上面有 .post(':id', ...) 吗?您发送请求以接收此错误的路线是什么?是 /test 吗?
  • 您是否使用过 ObjectId 类型的 _id 并将其分配为“测试”字符串?

标签: node.js mongodb mongoose


【解决方案1】:

您的代码顶部可能有一个.post(':id', ...)。因此,对/testRequest 的发布请求与'/:id''/testRequest' 路由匹配,但仅执行最上面的路由。 ':id' 路由读取 testRequest 作为 ID 并抛出 CastError。

您可以交换方法的顺序,这已经在here 讨论过。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-23
    • 2021-03-14
    • 2014-05-27
    • 1970-01-01
    • 1970-01-01
    • 2020-10-21
    • 2021-01-07
    相关资源
    最近更新 更多