mongoose-uuid-parser
UUID support for Mongoose (and MongoDB)
Motivation
There isn't an easy way to work with UUID and MongoDB in Javascript. Unless you use UUID as string, you will find yourself in trouble. This library offers some tools to set you free of this problem! :)
Getting started
yarn add mongoose-uuid-parser
npm install --save mongoose-uuid-parser
The easiest way to use it with mongoose is by injecting the UUID type to Schema Types. You can do it in some config file in your application.
const mongoose = ;const injectUUID = ; ;
And then in your Schema:
const schema = _id: type: mongooseSchemaTypesUUID default: utilv4 // generate new UUID V4 title: String description: String likedBy: mongooseSchemaTypesUUID versionKey: false ; const Post = "post" schema; { return await post;} { return await Post;} { const post = await ; console; // Binary console; // b2d239fe-7de2-4eee-85f6-a216fa3d7bb6 console; // b2d239fe-7de2-4eee-85f6-a216fa3d7bb6 const result = await ; console; //["c98b3119-2833-4d30-9e6d-182f3bd64301","02d79f3a-91d4-4c33-8db2-391cf4eaddd2"]} ;
Getter and Setter
Alternatively, instead of relying on UUID type, you can use the getter and setter provided by this library.
The example below shows how to use it in depth.
const mongoose = ;const getUUID setUUID util = ; const schema = _id: type: Object get: getUUID set: setUUID default: utilv4 // generate new UUID V4 title: String description: String likedBy: type: Object get: getUUID set: setUUID versionKey: false ; const Post = "post" schema; { return await post;} { // Should cast the id to search return await Post;} { const post = await ; console; // bae01115-c571-4bdc-9c0a-daa03c500030 console; // b2d239fe-7de2-4eee-85f6-a216fa3d7bb6 const result = await ; console; //["c98b3119-2833-4d30-9e6d-182f3bd64301","02d79f3a-91d4-4c33-8db2-391cf4eaddd2"]} ;
Extra utilities
Although you can find some useful tools for mongoose, all the conversion methods are available to use inside the util
object, so you can use it with the official mongoDB library.
const util = ; // Generate new UUIDlet uuid; uuid = util;console; // Binaryconsole // UUID String uuid = util;console // Binaryconsole // UUID String // Transform Binary to UUID String// Useful when you need to manually convert a Binary// Coming from MongoDBconst binary = util;const str = util; console // UUID String // Transform UUID String to Binary// Useful when you need to manually convert a string UUIDconst strUUID = util;const binaryUUID = util; console // Binaryconsole // UUID String
Contribute
You are welcome to send your PR!