Created
April 4, 2016 23:06
-
-
Save baruchvlz/1308f157cbbb580fcbfe0eabf585a299 to your computer and use it in GitHub Desktop.
MongoDB unique key generator.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* generateKey ( Because I don't like to use `_id` ) | |
* Generates a unique key | |
* @param Model -> Object | |
* @param Property Name (I.E. `clientId`) -> String | |
* @return Key -> String | |
**/ | |
export function generateKey(model, propName) { | |
// Algorythm for Key | |
const keyAlgo = () => { | |
return parseInt(Math.floor(Math.random() * 9000) + 1000) | |
} | |
let key = keyAlgo() | |
// Verify Key is unique | |
model.find({}, (err, result) => { | |
for(var i = 0; i < result.length; i++) { | |
if(result[i][propName] === key) | |
key = keyAlgo() | |
} | |
}) | |
return key.toString() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment