Alireza Valizade Alireza Valizade - 5 months ago 40
Node.js Question

token generator in node and express

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)=> {

else if(user){
}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


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.
        } else if (user) {
            // Try again.
        } 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) {
    } else {
        // Use the token here.