For a Node API I must generate a random alphanumeric key, this should be unique and SHORT (I can't use neither uuid or Mongo ObjectID).
I thought this logic:
- Generate key,
- Query MongoDB for key existance
- If key exists, repeat the process,
- If key doesn't exist, assign it and respond to client.
I tried then:
do {
key = randomKey(8);
newGroup.key = key;
Group.findOne({numberId: key}).then(function (foundGroup) {
console.log("cb");
if (! foundGroup) {
console.log("not found")
notUnique = false;
}
}).catch(function (err) {
return response.send(500);
});
} while (notUnique);
But only I got is an infinite loop, notUnique is never switching to true. Just in case, this was tested against an empy database.
How could I achieve it?