MongoDB Node check if objectid is valid

前端 未结 8 2371
甜味超标
甜味超标 2020-11-28 11:26

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

I tried :

var BSON = mongo.BSONPure;
console.log(\"Validity: \"  + BSON.ObjectID.is         


        
8条回答
  •  -上瘾入骨i
    2020-11-28 12:10

    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'
    

提交回复
热议问题