V
V
Vladimir T.2014-03-25 13:05:36
MongoDB
Vladimir T., 2014-03-25 13:05:36

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

1 answer(s)
V
Vladimir T., 2014-03-25
@vachuahe

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 question

Ask a Question

731 491 924 answers to any question