mongoose: [Bug - Mongoose >=4.7.3] Fail to create new record with string _id
When I try to create a new record with the “create” Model method by supplying the _id as a String,
Model.create({
_id: "5788683c1fa46a472a051543"
name: "abc"
});
it fails with the following error:
{"errors":{"_id":{"message":"Cast to ObjectID failed for value \"5788683c1fa46a472a051543\" at path \"_id\"","name":"CastError","stringValue":"\"5788683c1fa46a472a051543\"","kind":"ObjectID","value":"5788683c1fa46a472a051543","path":"_id","reason":{"message":"Cast to ObjectId failed for value \"5788683c1fa46a472a051543\" at path \"_id\"","name":"CastError","stringValue":"\"5788683c1fa46a472a051543\"","kind":"ObjectId","value":"5788683c1fa46a472a051543","path":"_id"}}},"message":"Model validation failed","name":"ValidationError"}
I suppose for Mongoose >= 4.7.3, it does not automatically convert string _id value to ObjectId _id value when we try to insert new records
About this issue
- Original URL
- State: closed
- Created 7 years ago
- Comments: 21 (3 by maintainers)
Links to this issue
Commits related to this issue
- Fixed mongoose bug by reverting to 4.7.2 https://github.com/Automattic/mongoose/issues/4867#issuecomment-270342054 — committed to jeffcooper86/heyfeedme.com by jeffcooper86 7 years ago
- mongoose downgrade: should use 4.7.2 for string objectIds — committed to wafflestudio/snutt by bekker 7 years ago
Also having this issue when retrieving records with a string ID using findById.
(err): CastError: Cast to ObjectId failed for value “586c6806a6918640e144622a” at path “_id” for model “User”
I have the same problem, at the moment I have “solve” it using the version 4.7.2. All posterior version have this bug. To install the version 4.7.2 you can use this command:
npm install mongoose@4.7.2
If you don’t specify id in your schema it should by default be ObjectId, also querying with a string instead of ObjectId should automatically cast, but it isn’t.
On Jan 4, 2017 10:30 AM, “joetidee” notifications@github.com wrote:
I think this is related to the upgrade of the bson package. See here https://github.com/Automattic/mongoose/issues/4860
…Although I have tried installing all dependencies so we get the latest version of bson and the bug persist… 😦
For now the solution is to use mongoose < 4.7.2 or upgrade node >= 6.0. If anyone else has any other ideas, feel free to comment, but i think this and waiting for js-bson to merge in PR 205 are the best solutions.
Make sure that if using a string for the _id, that you also have the following defined in your schema:
_id: {type: String}