I am doing MongoDB lookups by converting a string to BSON. Is there a way for me to determine if the string I have is a valid ObjectID for Mongo before doing the conversion?
@ross-u answer is just amazing.
I have chained the methods to do a full validation inline:
documentId = id && isValid(id) && new ObjectId(id) == id ? id : null
Note the double equal sign, which is VERY important as new ObjectId() does not return a string and strict comparison will return false when compared against a normal string (which I had coming in my logic).
The methods have been destructured from the mongoose object exposed by the require:
const {
Types: {
ObjectId: { isValid },
ObjectId
}
} = require("mongoose");