UUIDs With MongoDB and Node.js
Let's take a quick look at UUIDs with MongoDB and Node.js and also explore an example of how to use uuid-mongodb to query MongoDB.
Join the DZone community and get the full member experience.
Join For FreeMy team uses MongoDB quite heavily in a variety of our service backends. Some of these services interface with one another. For example, one service might request a resource by ID from another service and store that ID as a reference. To identify resources, we use UUIDs quite extensively due to their ubiquitous nature and general support.
MongoDB, like most databases, provide support for UUIDs, however using UUIDs with MongoDB and Node.js is not as trivial as one might expect (Note that I’m not going to touch on UUID complexities in multi-platform/multi-language scenarios).
First off, for performance reasons, it is highly beneficial to use BSON UUIDs, rather than UUID strings. BSON UUIDs represent UUIDs as binary data. This has the great advantage of providing improved overall performance, particularly with respect to queries.
Secondly, in order to use BSON UUIDs, a developer must wrangle with the pain of converting to and from Binary UUIDs and their string counterparts.
Thirdly, if using Node.js, you’ll find that neither the Native MongoDB Driver nor (the popular) Mongoose library provide a simple interface for BSON UUIDs. Instead, Node.js developers must work with generic Binary type. This type is rather general purpose and unfortunately, makes it relatively complicated to work with BSON UUIDs. Because of this, some developers give up and revert to strings. This is not recommended
All in all, my team and I found ourselves in this similar, painful place. Fortunately, we attempted to ease the burden for ourselves and hopefully for all of you. We developed a small Node.js library called uuid-mongodb that enables the straightforward usage of BSON UUIDs with Node.js. The library mitigates conversion pains and generates UUID’s that are 100% compatible with the Native MongoDB Driver. It is also compatible with Mongoose:
Let’s see an example of how to use uuid-mongodb to query MongoDB:
In this example, we convert a UUID string to a BSON UUID and use it in a query:
![](https://cdn-images-1.medium.com/max/1600/1*RS58Ot2IRqP3OGrd8EXQKQ.png)
In the next example, we execute a MongoDB query that returns a document containing a BSON UUID and convert it to a string:
![](https://cdn-images-1.medium.com/max/1600/1*JNIea3_vsEE3N8amz4m1ng.png)
All in all, uuid-mongodb aims to ease the burden of using BSON UUIDs with MongoDB. We hope you find it useful.
For those looking to contribute, provide feedback, or just use it in your Node.js application, go here.
Opinions expressed by DZone contributors are their own.
Comments