1

I trying create a function that generates a random token that doesn't exist in my database (Mongodb) and I use a unique property in my user schema. This is my function:

 var UniqueTokenGenerator = function () {

        var token = uuid.v4();
        UserModel.findOne({token : token} , (err , user)=> {

            if(err)
                res.status(500).send(err);
            else if(user){
                //1
            }else if(!user){
                 return token; //2
            }

        });

    };

My problems:

  1. I want if token exist call UniqueTokenGenerator or whatever... like loop.
  2. Token cannot be returned.
  3. Anybody has a better idea?

I don't want to use any library like jwt.

1 Answers1

1

Two answers:

First, you don't need to check the database to make sure your UUID is unique. UUIDs are so big that mathematically you won't run into a collision. See Are GUID collisions possible?

Second, to do what you're trying to do, you need to make your function asynchronous and deliver the result with a callback. E.g.

var generateUniqueToken = (callback) => {
    var token = uuid.v4();
    UserModel.findOne({ token: token }, (err, user) => {
        if(err) {
            // First parameter of the callback is an error.
            callback(err);
        } else if (user) {
            // Try again.
            generateUniqueToken(callback);
        } else if (!user) {
            // First parameter of the callback is an error. The second
            // parameter is the successful result.
            callback(null, token);
        }
    });
};

// Example usage:
generateUniqueToken((err, token) => {
    if (err) {
        res.status(500).send(err);
    } else {
        // Use the token here.
    }
});
Community
  • 1
  • 1
user94559
  • 59,196
  • 6
  • 103
  • 103
  • tnx for your answer...but 1% if 2 token get equal...?! –  Jun 28 '16 at 17:38
  • Yes, 1% chance if you generate 2.6 quintillion tokens. There are only 7.5 billion people on Earth. – user94559 Jun 28 '16 at 17:44
  • For a little perspective, if you created a UUID for every person on Earth, your odds of finding a collision would be roughly 0.0000000000000000000<<200,000 more zeros here>>0000001. It's more likely that you would be hit by a meteor twice in the next year than that you would find a collision. – user94559 Jun 28 '16 at 18:03