2

I return the Document _id and use it as a req.params.id to get the document at a later stage.

ObjectId.isValid() returns true, then using it in either ObjectId() or Find or FindOne will result in a cast error or

hex is not a function.

Basically also copy pasted the _id straight from the database to test.

I'm using mongoose ^4.7.6; _id looks like: 586e30a597f85b69891df304

[Stack trace]

[CastError: Cast to ObjectId failed for value "586e30a597f85b69891df304" at path "_id" for model "Module"] message: 'Cast to ObjectId failed for value "586e30a597f85b69891df304" at path "_id" for model "Module"', name: 'CastError', stringValue: '"586e30a597f85b69891df304"', kind: 'ObjectId', value: '586e30a597f85b69891df304', path: '_id', reason: undefined,

Ivan Chernykh
  • 41,617
  • 13
  • 134
  • 146
Kevin Toet
  • 367
  • 4
  • 16
  • "hex is not a function" does not sound like Mongoose refuses to cast. It sounds more like a bug either in your or somebody else's code. Please post the whole stacktrace of the error. – str Jan 05 '17 at 12:35
  • added part of the trace, though cant seem to format correctly – Kevin Toet Jan 05 '17 at 12:37
  • Possible duplicate of [Cast to ObjectId failed for value "586cc8b3ea780c071bbe2469" at path "\_id" for model "User"](http://stackoverflow.com/questions/41461562/cast-to-objectid-failed-for-value-586cc8b3ea780c071bbe2469-at-path-id-for-m) – Mete Erzincanlı Jan 15 '17 at 15:59

2 Answers2

3

this is a bug in Mongoose >=4.7.3 https://github.com/Automattic/mongoose/issues/4867

bson package is really buggy

Trej Gun
  • 1,006
  • 1
  • 8
  • 11
1

Turns out it's a bug in that version of mongoose. Removing my node_modules and reinstalling with mongoose set to 4.3.3 fixed this issue.

Kevin Toet
  • 367
  • 4
  • 16