Randomly generating a value not in mongodb?

Viewed 1253

I'm trying to generate session ids in Node and store them in MongoDB. For my application I only want to generate a random 6 digit number (this number is used to sync two sessions so it's short for users to easily copy). I want to generate a number that is not already in my sessions collection in MongoDB. My first thought which will probably work 99% of the time is this:

function GetSessionKey(cb) {
    var key = parseInt(Math.random() * 1000000).toString();
    while (key.length < 6) key = '0' + key;
    db.sessions.find({ Key: key }, function (err, docs) {
        if (!err && docs.length == 0) {
            cb(key);
        } else {
            GetSessionKey(cb);
        }
    });
}

But there is a slim chance that the generated key constantly picks existing keys in mongo. Or the possibility that all keys are already in use (which I do not expect to happen).

I know Node is asynchronous but does that mean that a recursive async call like this will fill up the stack if it keeps getting called? Or do async calls not get put on the stack? Is there a better way to generate short unique keys? Old keys will be removed and can be reused so I don't think it's be a ticking time bomb. I'm just worried that the random aspect may cause trouble.

2 Answers
Related