Skip to content

Instantly share code, notes, and snippets.

@baruchvlz
Created April 4, 2016 23:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save baruchvlz/1308f157cbbb580fcbfe0eabf585a299 to your computer and use it in GitHub Desktop.
Save baruchvlz/1308f157cbbb580fcbfe0eabf585a299 to your computer and use it in GitHub Desktop.
MongoDB unique key generator.
/**
* 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