MongoDB Node check if objectid is valid

2019-01-07 23:15发布

问题:

How can I check whether an ObjectID is valid using Node's driver

I tried :

var BSON = mongo.BSONPure;
console.log("Validity: "  + BSON.ObjectID.isValid('ddsd'))

But I keep getting an exception instead of a true or false. (The exception is just a 'throw e; // process.nextTick error, or 'error' event on first tick'

回答1:

Not sure where the isValid() function comes from but it's not in node-mongodb-native.

You could use this Regular Expression if you want to check for a string of 24 hex characters.

var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$");

Taken from github.com/mongodb/js-bson/.../objectid.js



回答2:

isValid() is in the js-bson library, which is a dependency of node-mongodb-native.

For whoever finds this question, I don't recommend recreating this method as recommend in other answers. Instead continue using node-mongodb-native like the original poster was using, the following example will access the isValid() method in js-bson.

var mongodb = require("mongodb"),
    objectid = mongodb.BSONPure.ObjectID;

console.log(objectid.isValid('53fbf4615c3b9f41c381b6a3'));

July 2018 update: The current way to do this is:

var mongodb = require("mongodb")
console.log(mongodb.ObjectID.isValid(id))


回答3:

As an extension of Eat at Joes answer... This is valid in node-mongodb-native 2.0

var objectID = require('mongodb').ObjectID

objectID.isValid('54edb381a13ec9142b9bb3537') - false
objectID.isValid('54edb381a13ec9142b9bb353') - true
objectID.isValid('54edb381a13ec9142b9bb35') - false


回答4:

@GianPaJ's snippet is great but it needs to be extended slightly to cover non hex objectID's. Line 32 of the same file indicates objectID's can also be 12 characters in length. These keys are converted to a 24 character hex ObjectID by the mongodb driver.

function isValidObjectID(str) {
  // coerce to string so the function can be generically used to test both strings and native objectIds created by the driver
  str = str + '';
  var len = str.length, valid = false;
  if (len == 12 || len == 24) {
    valid = /^[0-9a-fA-F]+$/.test(str);
  }
  return valid;
}


回答5:

I have submitted a pull-request to the js-bson library which exposes an isValid method, as the logic to check the objectid string was already in there.



回答6:

You can use Cerberus and create a custom function to validate and ObjectId

from cerberus import Validator
import re

class CustomValidator(Validator): 
    def _validate_type_objectid(self, field, value):
        """ 
        Validation for `objectid` schema attribute.

        :param field: field name.
        :param value: field value.
        """
        if not re.match('[a-f0-9]{24}', str(value)):
            self._error(field, ERROR_BAD_TYPE % 'ObjectId')

## Initiate the class and validate the information
v = CustomValidator()

schema = {
    'value': {'type': 'objectid'}
}
document = {
    'value': ObjectId('5565d8adba02d54a4a78be95')
}

if not v(document, schema):
    print 'Error'