Alexandre Senges
Alexandre Senges

Reputation: 1599

Mongoose CastError

I have the following code, which does absolutely nothing, and for some reasons, I have an error with mongoose which is not even called, here's the code:

.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);
    }
  })

And here's the error:

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,

I've tried many things but didn't seem to fix it

Upvotes: 1

Views: 321

Answers (1)

Murilo
Murilo

Reputation: 173

You probably have a .post(':id', ...) on top of your code. So a post request to /testRequest matches the '/:id' and '/testRequest' routes, but only the top one executes. The ':id' route reads testRequest as an ID and throws the CastError.

You can swap the order of the methods, which was already discussed here.

Upvotes: 2

Related Questions