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?
Below is a function that both checks with the ObjectId isValid method and whether or not new ObjectId(id) returns the same value. The reason for isValid not being enough alone is described very well by Andy Macleod in the chosen answer.
const ObjectId = require('mongoose').Types.ObjectId;
/**
* True if provided object ID valid
* @param {string} id
*/
function isObjectIdValid(id){
return ObjectId.isValid(id) && new ObjectId(id) == id;
}