0

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!

  • The function you assign to `getAvailableHash` doesn't have a `return` statement – Quentin Jun 06 '18 at 11:02
  • Yes, you're missing `return`. It should be as in `return getAvailableHash();` – Ishan Madhusanka Jun 06 '18 at 11:09
  • What about `return generatedHash;` in the Mongoose function? I guess that only returns it to that function? Oh, but I take it if I added 'return' before that function it would return it to the `getAvailableHash` one. That does make sense. Will also look into the post you linked. Thank you! – JRWashington Jun 06 '18 at 11:12

0 Answers0