MongoDB Node check if objectid is valid

前端 未结 8 2375
甜味超标
甜味超标 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: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;
    }
    

提交回复
热议问题