猫鼬:二进制子类型4到字符串

时间:2018-08-22 21:17:47

标签: node.js mongodb mongoose

我对mongo进行查询,该查询返回一个UUID作为Bin4。如何将其转换为字符串?

Binary {
  _bsontype: 'Binary',
  sub_type: 4,
  position: 16,
  buffer: <Buffer 93 02 fc 42 a9 6b 47 7b ab 63 5c 78 c1 07 3a 2c> }

我期望得到的回报是这样的9302FC42-A96B-477B-AB63-5C78C1073A2C

我尝试过JSON.parse(JSON.stringify(userData._id)),得到的是这个kwL8QqlrR3urY1x4wQc6LA==

我还能做什么?

1 个答案:

答案 0 :(得分:0)

您可以尝试:print(BinData(4,“ kwL8QqlrR3urY1x4wQc6LA ==”));

您将获得输出为UUID(“ 9302fc42-a96b-477b-ab63-5c78c1073a2c”) 您可以将其转换为如下字符串:

var x = BinData(4, "kwL8QqlrR3urY1x4wQc6LA==");

function ToUUID(hex) {
    var a =  hex.substr(0, 2) + hex.substr(2, 2)  + hex.substr(4, 2) + hex.substr(6, 2);
    var b =  hex.substr(8, 2) + hex.substr(10, 2);
    var c =  hex.substr(12, 2) + hex.substr(14, 2);
    var d = hex.substr(16, 16);
    hex = a + b + c + d;
    var uuid = hex.substr(0, 8) + '-' + hex.substr(8, 4) + '-' + hex.substr(12, 4) + '-' + hex.substr(16, 4) + '-' + hex.substr(20, 12);
    return '"' + uuid + '"';
}

var z = ToUUID(x.hex());
print(z);