bug in mongoose.Types.ObjectId.isValid()
See original GitHub issuebug in mongoosejs 6.1.6 version:
ObjectId.isValid validates an Object with prop id as a valid ObjectId:
mongoose.Types.ObjectId.isValid({ id: '580e0797bb495f0a200e91ad' }) // true
But in 6.1.5 this is an invalid ObjectId
mongoose.Types.ObjectId.isValid({ id: '580e0797bb495f0a200e91ad' }) // false
Issue Analytics
- State:
- Created 2 years ago
- Comments:9
Top Results From Across the Web
ObjectId.isValid() returns true for non-object IDs - MongoDB
Using the ObjectId.isValid() method from the mongodb nodejs package isn't enough, it returns true for any string that contains 12 characters.
Read more >mongoose isValidObjectId() always returns false
I'm having a weird issue with isValidObjectID() in mongoose, which appeared after I added TypeScript to my Node project and had to update ......
Read more >Mongoose v6.8.2: API docs
isObjectIdOrHexString() returns true only for ObjectId instances or 24 character hex strings, and will return false for numbers, documents, and strings of ...
Read more >cast to [objectid] failed for value - You.com | The AI Search ...
Mongoose's findById method casts the id parameter to the type of the model's _id field so that it can properly query for the...
Read more >How to check if a string is valid MongoDB ObjectId in Node.js
Mongoose & MongoDB provide a very useful function in ObjectId i.e. ObjectId.isValid(“some_id”) to validate a string for correct MongoDB ID.
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
@Maximusya thx for the help.
re-checked and found that the isValid changed behaviour from bson@4.6.0 to bson@4.6.1
So the issue is caused by bson npm module.
This PR causes the change in the isValid behaviour: https://github.com/mongodb/js-bson/pull/475
isValid now also accepts ObjectIdLike type, which matches an object like { id: ‘580e0797bb495f0a200e91ad’} 580e0797bb495f0a200e91ad
Defined in file on line 13: https://github.com/mongodb/js-bson/blob/master/src/objectid.ts
@maximilianschmid can you please elaborate why this is a breaking change? The intent of
isValid()
andisValidObjectId()
is to check whether a value is something that can be converted to an ObjectId, and growing the set of objects that can be converted to ObjectIds is at worst a semver minor. We can consider explicitly avoiding casting{ id: <string> }
as an ObjectId if that causes problems.In the meantime, as per @Uzlopak 's suggestion, we’ll make
isValidObjectId()
consistent withisValid()
. There’s no reason for us to mix/match rules as to what is a valid ObjectId anymore.