Answer the question
In order to leave comments, you need to log in
How to check if a variable is a valid ObjectID?
In mongoDB, the document id (default) _id is of type ObjectID.
How can node.js check if a variable (string) is a valid ObjectID so that the application does not crash when a string variable is cast to this type, for example, by such code?var user_id = new objectID(req.query.user_id );
Answer the question
In order to leave comments, you need to log in
ObjectID has a validation function, but it is not available as a method.
pull request which should fix this for version 3
https://github.com/mongodb/js-bson/pull/65
meanwhile do it yourself:
function isValidObjectID(str) {
str = str + '';
var len = str.length, valid = false;
if (len == 12 || len == 24) {
valid = /^[0-9a-fA-F]+$/.test(str);
}
return valid;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question