https://github.com/cdimascio/uuid-mongodb
📇 Generates and parses MongoDB BSON UUIDs
https://github.com/cdimascio/uuid-mongodb
binary bson hacktoberfest mongo mongodb mongoose nodejs uuid
Last synced: 17 days ago
JSON representation
📇 Generates and parses MongoDB BSON UUIDs
- Host: GitHub
- URL: https://github.com/cdimascio/uuid-mongodb
- Owner: cdimascio
- License: mit
- Created: 2018-07-22T19:00:59.000Z (almost 7 years ago)
- Default Branch: master
- Last Pushed: 2024-12-03T04:58:55.000Z (6 months ago)
- Last Synced: 2025-05-09T13:50:32.188Z (23 days ago)
- Topics: binary, bson, hacktoberfest, mongo, mongodb, mongoose, nodejs, uuid
- Language: JavaScript
- Homepage:
- Size: 540 KB
- Stars: 101
- Watchers: 3
- Forks: 17
- Open Issues: 13
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGE_HISTORY.md
- License: LICENSE
Awesome Lists containing this project
README
# uuid-mongodb
 [](https://www.codacy.com/app/cdimascio/uuid-mongodb?utm_source=github.com&utm_medium=referral&utm_content=cdimascio/uuid-mongodb&utm_campaign=Badge_Grade)   [](#contributors)
Generates and parses [BSON UUIDs](https://docs.mongodb.com/manual/reference/method/UUID/) for use with MongoDB. BSON UUIDs provide better performance than their string counterparts.
![]()
Inspired by [@srcagency's](https://github.com/srcagency) [mongo-uuid](https://github.com/srcagency/mongo-uuid)
## Install
```shell
npm install uuid-mongodb
```## Usage
```javascript
const MUUID = require('uuid-mongodb');// Create a v1 binary UUID
const mUUID1 = MUUID.v1();// Create a v4 binary UUID
const mUUID4 = MUUID.v4();// Print a string representation of a binary UUID
mUUID1.toString()// Create a binary UUID from a valid uuid string
const mUUID2 = MUUID.from('393967e0-8de1-11e8-9eb6-529269fb1459')// Create a binary UUID from a MongoDb Binary
// This is useful to get MUUIDs helpful toString() method
const mUUID3 = MUUID.from(/** MongoDb Binary of SUBTYPE_UUID */)
```## Formatting
UUIDs may be formatted using the following options:
Format | Description | Example
-- | -- | --
N | 32 digits | `00000000000000000000000000000000`
D | 32 digits separated by hyphens | `00000000-0000-0000-0000-000000000000`
B | 32 digits separated by hyphens, enclosed in braces | `{00000000-0000-0000-0000-000000000000}`
P | 32 digits separated by hyphens, enclosed in parentheses | `(00000000-0000-0000-0000-000000000000)`**example:**
```javascript
const mUUID4 = MUUID.v4();
mUUID1.toString(); // equivalent to `D` separated by hyphens
mUUID1.toString('P'); // enclosed in parens, separated by hypens
mUUID1.toString('B'); // enclosed in braces, separated by hyphens
mUUID1.toString('N'); // 32 digits
```## Modes
uuid-mongodb offers two modes:
- **canonical** (default) - A string format that emphasizes type preservation at the expense of readability and interoperability.
- **relaxed** - A string format that emphasizes readability and interoperability at the expense of type preservation.The mode is set **globally** as such:
```javascript
const mUUID = MUUID.mode('relaxed'); // use relaxed mode
```Mode _**only**_ impacts how `JSON.stringify(...)` represents a UUID:
e.g. `JSON.stringy(mUUID.v1())` outputs the following:
```javascript
"DEol4JenEeqVKusA+dzMMA==" // when in 'canonical' mode
"1ac34980-97a7-11ea-8bab-b5327b548666" // when in 'relaxed' mode
```## Examples
**Query using binary UUIDs**
```javascript
const uuid = MUUID.from('393967e0-8de1-11e8-9eb6-529269fb1459');
return collection.then(c =>
c.findOne({
_id: uuid,
})
);
```**Work with binary UUIDs returned in query results**
```javascript
return collection
.then(c => c.findOne({ _id: uuid }))
.then(doc => {
const uuid = MUUID.from(doc._id).toString();
// do stuff
});
```## Examples (with source code)
#### Native Node MongoDB Driver example
- [examples/ex1-mongodb.js](examples/ex1-mongodb.js)
**snippet:**
```javascript
const insertResult = await collection.insertOne({
_id: MUUID.v1(),
name: 'carmine',
});
```#### Mongoose example
- [examples/ex2-mongoose.js](examples/ex2-mongoose.js)
**snippet:**
```javascript
const kittySchema = new mongoose.Schema({
_id: {
type: 'object',
value: { type: 'Buffer' },
default: () => MUUID.v1(),
},
title: String,
});
```- [examples/ex3-mongoose.js](examples/ex3-mongoose.js)
**snippet:**
```javascript
// Define a simple schema
const kittySchema = new mongoose.Schema({
_id: {
type: 'object',
value: { type: 'Buffer' },
default: () => MUUID.v1(),
},
title: String,
});
// no need for auto getter for _id will add a virtual later
kittySchema.set('id', false);
// virtual getter for custom _id
kittySchema
.virtual('id')
.get(function() {
return MUUID.from(this._id).toString();
})
.set(function(val) {
this._id = MUUID.from(val);
});
```- [examples/ex4-mongoose.js](examples/ex4-mongoose.js)
```javascript
const uuid = MUUID.v4();// save record and wait for it to commit
await new Data({ uuid }).save();// retrieve the record
const result = await Data.findOne({ uuid });
```## Notes
Currently supports [UUID v1 and v4](https://www.ietf.org/rfc/rfc4122.txt)
## Contributors
Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
Carmine DiMascio
💻
Benjamin Dobell
💻
David Pfeffer
💻
This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!
## License
[MIT](./LICENSE)