Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to read data in nodejs with mongodb which is persisted using C# with GUIDs

I have seen a few questions around this but none of them seem to directly solve the issue here.

So the scenario is there is a C# based API which writes data to a mongodb instance and uses a GUID as the _id in mongo, so for example it would look like:

"_id" : new BinData(3, "+jscvebAl0+NO0n1WySLTQ=="),

So assume that it not going to change, it will always be that data type and there is nothing I can do about it.

So in nodejs I read in a document which contains some of these UUID which relate to other resources, however when I read in the documents using the nodejs 2.0 driver the UUID vars are read in as GUID strings, like so:

"someIdField": "c1489470-4e04-49ba-ae91-a20c009254e5"

So if I were to directly use { "_id" : someIdField } it doesn't find the matching document, and I assume its because it needs to compare against the binary representation, not the string one, however I cannot seem to turn that string into something worthwhile.

I have tried using the npm uuid package to parse and then use that buffer like so:

var bytes = Uuid.parse(uuid);
return new Binary(new Buffer(bytes), 3);

However that doesnt seem to work and I have tried other solutions including base64 encoding but nothing seems to bring back results. So is there anything else I need to be doing here?

like image 984
Grofit Avatar asked Oct 25 '25 21:10

Grofit


1 Answers

Ok so I have got it working, and it was painful but after looking at the UUIDHelpers and some other code on stackoverflow it seems that this is the method I needed to get my stuff running:

module.exports = function(uuid) {
    var hex = uuid.replace(/[{}-]/g, ""); // remove extra characters
    var a = hex.substr(6, 2) + hex.substr(4, 2) + hex.substr(2, 2) + hex.substr(0, 2);
    var b = hex.substr(10, 2) + hex.substr(8, 2);
    var c = hex.substr(14, 2) + hex.substr(12, 2);
    var d = hex.substr(16, 16);
    hex = a + b + c + d;
    var buffer= new Buffer(hex, "hex");
    return new Binary(buffer, Binary.SUBTYPE_UUID_OLD);
};

That should turn a textual guid into a binary representation of a legacy guid.

like image 193
Grofit Avatar answered Oct 27 '25 11:10

Grofit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!