Can someone explain this recursive function MongooseJS Can someone explain this recursive function MongooseJS mongoose mongoose

Can someone explain this recursive function MongooseJS


checkIfSlugExists function in your example ensures that there is no documents with slugToFind slug in database already.

checkIfSlugExists not simply checks that the slug if vacant, but it also has some failover mechanisms. So, in the end it returns a promise to a vacant slug:

  1. If slugToFind don't exist in database, then it's returned (line 331).
  2. Otherwise checkIfSlugExists checks for a longSlug (lines 338-341), which is just a longer version of the original slugToFind.
  3. If both slugToFind and longSlug are already taken, then checkIfSlugExists starts adding numbers to longSlug (line 344-355), starting from 2, untill it finds a vacant slug.

Every time checkIfSlugExists wants to check for some new slug it recursively calls itself with this new value.