Mongoose refuses to cast valid string to ObjectId

纵饮孤独 提交于 2019-12-08 13:17:24

问题


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,


回答1:


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

bson package is really buggy




回答2:


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.



来源:https://stackoverflow.com/questions/41485198/mongoose-refuses-to-cast-valid-string-to-objectid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!