1

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

Alexandre Senges
  • 1,474
  • 1
  • 13
  • 22
  • you can refer to this solution https://stackoverflow.com/questions/34985332/express-mongoose-router-cast-to-objectid-failed-for-value-undefined-at-path – Sanjaysinh Zala Sep 19 '18 at 04:08
  • 1
    Do you have a .post(':id', ...) on top of this code? What route you are sending the request to receive this error? Is it /test ? – Murilo Sep 19 '18 at 04:32
  • have you used _id with type ObjectId and assigning it "test" string? – Shivam Pandey Sep 19 '18 at 04:54

1 Answers1

2

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.

Murilo
  • 173
  • 1
  • 4