Seun Akanni
Seun Akanni

Seun Akanni

Checking if string is an ObjectId in MongoDB using Mongoose

Checking if string is an ObjectId in MongoDB using Mongoose

Seun Akanni's photo
Seun Akanni

Published on Jul 8, 2020

1 min read

Problem

Using mongoose.Types.ObjectId.isValid to check if an ObjecId is valid and not a random string will return TRUE for any string of 12 bytes, this could be catastrophic.

Screenshot 2020-07-08 at 6.18.15 PM.png

Solution

To solve this, I suggest you create a new ObjectId using the string, then compare the results. ObjectId will always return thesame value if its a true

Screenshot 2020-07-08 at 6.25.38 PM.png

 
Share this