Skip to content

srcagency/mongo-uuid

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

28 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Mongo UUID

When saving a UUID in MongoDB, you probably want to save the binary data in their native format. This helper is meant to ease that.

const m = require('mongodb') // "mongodb-core" or "bson" work as well
const u = require('mongo-uuid')

const uuid = (i) => u(m.Binary, i)

const id = uuid()
// -> Binary

console.log(u.stringify(id))
// -> fa4aab39-bdd8-406c-9813-6206433912e9

uuid('fa4aab39-bdd8-406c-9813-6206433912e9')
// -> Binary

API

Binary should be the Binary constructor from the BSON package.

Create

u.create(Binary)
u(Binary)

Parse

u.parse(Binary, 'dcc090ea-a65b-4ea4-9d91-22310bdad8af')
u(Binary, 'dcc090ea-a65b-4ea4-9d91-22310bdad8af')

Parse might throw a ParseError. The error class is exposed as u.ParseError for recognizing and catching.

Stringify

u.stringify(uuid) // dcc090ea-a65b-4ea4-9d91-22310bdad8af

Is valid

Check if the input is a valid UUID string without throwing.

u.isValid('dcc090ea-a65b-4ea4-9d91-22310bdad8af') // true

Examples

const {join} = require('bluebird')
const {Binary, MongoClient} = require('mongodb')
const uuid = require('mongo-uuid')

const uuid = (i) => u(Binary, i)

const client = new MongoClient('mongodb://localhost:27017/myproject')
const db = client.db()

// Creating documents

const id = uuid()

const insert = db
	.collection('docs')
	.insertOne({
		_id: id,
	})
	.then(() => console.log('Inserted with ID', uuid.stringify(id)))

// Finding documents

const id = uuid('dcc090ea-a65b-4ea4-9d91-22310bdad8af')

join(insert, () =>
	db
		.collection('docs')
		.find({
			_id: id,
		})
		.limit(1)
		.next()
).then(console.log)

About

Helps you save UUID in MongoDB

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published