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?
It took me a while to get a valid solution as the one proposed by @Andy Macleod of comparing objectId value with its own string was crashing the Express.js server on:
var view_task_id_temp=new mongodb.ObjectID("invalid_id_string"); //this crashed
I just used a simple try catch to solve this.
var mongodb = require('mongodb');
var id_error=false;
try{
var x=new mongodb.ObjectID("57d9a8b310b45a383a74df93");
console.log("x="+JSON.stringify(x));
}catch(err){
console.log("error="+err);
id_error=true;
}
if(id_error==false){
// Do stuff here
}
You can use a regular expression to test for that:
CoffeeScript
if id.match /^[0-9a-fA-F]{24}$/
# it's an ObjectID
else
# nope
JavaScript
if (id.match(/^[0-9a-fA-F]{24}$/)) {
// it's an ObjectID
} else {
// nope
}
For mongoose , Use isValid() function to check if objectId is valid or not
Example :
var ObjectId = mongoose.Types.ObjectId;
if(ObjectId.isValid(req.params.documentId)){
console.log('Object id is valid');
}else{
console.log('Invalid Object id');
}
Warning: isValid will return true for arbitrary 12/24 length strings beginning with a valid hex digit. Currently I think this is a better check:
((thing.length === 24 || thing.length === 12) && isNaN(parseInt(thing,16)) !== true)
The only way i found is to create a new ObjectId with the value i want to check, if the input is equal to the output, the id is valid :
function validate(id) {
var valid = false;
try
{
if(id == new mongoose.Types.ObjectId(""+id))
valid = true;
}
catch(e)
{
valid = false;
}
return valid;
}
> validate(null)
false
> validate(20)
false
> validate("abcdef")
false
> validate("5ad72b594c897c7c38b2bf71")
true
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;
}