Below is a function I wrote that generates a random string that gets passed into a 'generatedHash' variable. Then I am trying to find the hash in the database, if it doesn't exist it should return the hash that was generated, if however it does exist, it should run the same function again until it generates a hash that doesn't already exist. However, each time I run it returns as undefined. The way I use the getAvailableHash function is by directly calling it as the value for the hash field when creating the object that will be saved to the Mongo database via Mongoose.
const getAvailableHash = () => {
const generatedHash = randomstring.generate({
length: 10,
charset: 'alphanumeric'
});
// Check if hash exists
Link.findOne({ hash: generatedHash }).then(retrieveHash => {
if (!retrieveHash) {
return generatedHash;
} else {
getAvailableHash();
}
});
};
I tried finding a solution for this and heard people talk about wrapping the item I want to return in a callback() function, but I also tried that and it didn't work for me. Any help of pointing me in the right direction would be appreciated. Thanks!