How to work with Binary or UUID types inside Mongo server-side javascript?

Viewed 478

I am storing binary UUIDs in mongoDB, using them as indexes. This works great, thanks to the mongo-uuid library that I'm using from node.js

However, I'm now attempting to work with these UUIDs in other contexts, namely inside a server-side script I'm running as a mapReduce function. Basically, I'm searching for UUID-like codes in each document to form associative links between objects. This code works great, but I've got a problem dealing with the binary UUID fields.

I've found that I can convert hex code to UUID by doing

var uuid = UUID(<hex string>)

but that there is no inverse function to get from binary object to hex code. It appears that within the Mongo framework, there is no access to the Binary.value(), and the UUID() object has no stringify call.

The best workaround I've found is this:

   var uuid = UUID(); // Some BSON UUID instance
   var uuid_str = uuid.toString()  // Resolves to "UUID(\"abcdabcd-...-12345678\")"
                      .substring(6,32); // Take out the hex code

However, this makes me nervous, since it's a bit of a hack - is there any more robust method?

Moreover, there are issues sometimes when exporting the Mongo documents that contain binary UUIDs. To get around this, I've taken to using the binary UUID only in the key field, and using string UUIDs to refer to other documents.

Can anyone shed any further light on how to manipulate the BSON binary classes inside server-side javascript, or on how to change the default toString behavior of BSON types in node?

0 Answers
Related