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?
I have used the native node mongodb driver to do this in the past. The isValid method checks that the value is a valid BSON ObjectId. See the documentation here.
var ObjectID = require('mongodb').ObjectID;
console.log( ObjectID.isValid(12345) );
If you are using Mongoose, we can test whether a String is of 12 bytes or a string of 24 hex characters by using isValidObjectId.
mongoose.isValidObjectId(string) will return true/false
This is a upgraded solution provided by accepted solution .
The easiest way is basically wrap your ObjectId method in a try and catch service. Then you are using this service to handle Objecet Id's, instead of using the method directly:
var ObjectId = REQUIRE OR IMPORT ...
// service
function oid(str) {
try {
return ObjectId(str);
} catch(err) {
return false;
}
}
// usage
if (oid(USER_INPUT)) {
// continue
} else {
// throw error
}
You can also send null or empty props to get a new generated ID.
In the solution answer Andy Macleod said:
What has been working for me is casting a string to an objectId and then checking that the original string matches the string value of the objectId.
new ObjectId('timtamtomted'); //616273656e6365576f726b73 new ObjectId('537eed02ed345b2e039652d2') //537eed02ed345b2e039652d2
This work because valid ids do not change when casted to an ObjectId but a string that gets a false valid will change when casted to an objectId.
An implementation of this approach, would be a function that checks if the passed value is a valid ObjectId
and works with both string
and ObjectId
(object) values. It would look something like this:
var ObjectId = require("mongoose");.Types.ObjectId;
function isValidObjectId(value) {
// If value is an object (ObjectId) cast it to a string
var valueString = typeof value === "string" ? value : String(value);
// Cast the string to ObjectId
var idInstance = new ObjectId(valueString);
return String(idInstance) === valueString;
}
mongoose.Types.ObjectId.isValid(string) always returns True if string contains 12 letters
let firstUserID = '5b360fdea392d731829ded18';
let secondUserID = 'aaaaaaaaaaaa';
console.log(mongoose.Types.ObjectId.isValid(firstUserID)); // true
console.log(mongoose.Types.ObjectId.isValid(secondUserID)); // true
let checkForValidMongoDbID = new RegExp("^[0-9a-fA-F]{24}$");
console.log(checkForValidMongoDbID.test(firstUserID)); // true
console.log(checkForValidMongoDbID.test(secondUserID)); // false
The simplest way to check if the string is a valid Mongo ObjectId is using mongodb module.
const ObjectID = require('mongodb').ObjectID;
if(ObjectID.isValid(777777777777777)){
console.log("Valid ObjectID")
}