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:
- If
slugToFind
don't exist in database, then it's returned (line331
). - Otherwise
checkIfSlugExists
checks for alongSlug
(lines338-341
), which is just a longer version of the originalslugToFind
. - If both
slugToFind
andlongSlug
are already taken, thencheckIfSlugExists
starts adding numbers tolongSlug
(line344-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.