Attempting a find operation 5 times in node

I am generating a token using "hat".

I am trying to write very paranoid code. So, the idea is that the system generates an ID, checks if it's already taken (querying the DB), and if it hasn't, it returns it. If it has, tries again, 5 times. After 5 times, something very strange is going on and the application throws an error.

The short question is: how can I make this code run 5 times, in sequence, with the option of calling the passed callback (see, "quit" the cycle) if the token is actually available?

Is is the code that only attempts once:

var hat = require('hat'),
mongoose = require('mongoose');

exports.makeToken = function( callback ){

  Workspace = mongoose.model("Workspace");

  var found = false;
  var token;

  // Generate the token, check that it's indeed available
  token = hat();
  Workspace.findOne( { 'access.token':token } , function(err, doc){
    if(err){
      callback(err, null);
    } else {
      if( doc ){
        callback( new Error("Cannot generate unique token"), null );
      } else {
        callback(null, token );
      }
    }
  });
}

I think you are paranoid. Why are you doing this? Why 5 times?

Putting that to one side. All you should be doing is asking the db once weather the token exists or not. If you get a result then token is in use, if not then taken has not been used. End of story.

As I mentioned in your previous question you don't even need to generate a token as you can use mongodb's native ObjectId as you unique identifier, that's assuming you store a separate document for each 'user'.

Unfortunately, I cannot use the ObjectId because 1) The user might decide to regenerate the token key 2) Users are not stored as individual documents.

So, there is a chance that the token generated is not unique, which would give me a situation where there is the same token ID for two user<->workspace pair, which wouldn't be good. Hence, the 5 attempts. I ADMIT that chances are pretty slim, but still...

I came up with this (recursion is needed here):

var hat = require('hat'),
mongoose = require('mongoose');

exports.makeToken = function( callback ){

  var attempts = 0;
  look();

  function look(){
    Workspace = mongoose.model("Workspace");

    // Generate the token, check that it's indeed available
    var token = hat();
    Workspace.findOne( { 'access.token':token } , function(err, doc){

      // There is an error: throw it straight away
      if(err){
        callback(err, null);
      } else {

        // Token already there: either give up (too many attempts)...
        if( !doc ){
          attempts ++;
          if( attempts == 5 ){
            callback( new Error("Cannot generate unique token"), null );
          } else {
            look();
          }
        // ... or try again by calling this function again!
        } else {
          callback(null, token );
        }
      }
    });
  }
}