MongoDB Node check if objectid is valid

前端 未结 8 2372
甜味超标
甜味超标 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条回答
  • 2020-11-28 12:05

    Follow this regular expression :

    in js

    new RegExp("^[0-9a-fA-F]{23}$").test("5e79d319ab5bfb2a9ea4239")

    in java

    Pattern.compile("^[0-9a-fA-F]{23}$").matcher(sanitizeText(value)).matches()

    0 讨论(0)
  • 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'
    
    0 讨论(0)
  • 2020-11-28 12:13

    isValid() is in the js-bson (objectid.ts) 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");
    var 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))
    
    0 讨论(0)
  • 2020-11-28 12:14

    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
    
    0 讨论(0)
  • 2020-11-28 12:20

    @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;
    }
    
    0 讨论(0)
  • 2020-11-28 12:21

    If you are using mongoose then you can use mongoose for validation rather than depending on any other library.

    if (!mongoose.Types.ObjectId.isValid(req.id)) {
        return res.status(400).send("Invalid object id");
    }
    
    0 讨论(0)
提交回复
热议问题