Home > Net >  Best way to generate unique string based on its existence in mongoDB
Best way to generate unique string based on its existence in mongoDB

Time:06-24

I'm making an URL shortener and need to check if the generated short URL doesn't already exist in the db to avoid data corruption.

I'm using node and express with mongodb and mongoose. This is the algorithm that I came up with, but I'm really not a fan of it. Is there any way I could do this in a more clean way?

while(true){
            var shortURLString = utils.makeShortURLString();
            var dbQuery = URL.findOne({shortURL: shortURLString});
            if(typeof dbQuery.fullURL == 'undefined'){
                const URL_obj = new URL({fullURL: req.body.inputURL, shortURL: shortURLString});
                await URL_obj.save();
                const shortURL = req.get('host') "/" URL_obj.shortURL
                const fullURL = URL_obj.fullURL;
                res.render('shortenedURL', {shortURL: shortURL, fullURL: fullURL});
                break;
            }
        }

Any other criticism/input is welcomed too!

CodePudding user response:

The only way I see that I can optimize it a bit:

let shortURL

do shortURL = utils.makeShortURLString();
while (URL.findOne({ shortURL }))

const URL_obj = (new URL({fullURL: req.body.inputURL, shortURL})).save()

const shortURL = req.get('host')   "/"   URL_obj.shortURL

res.render('shortenedURL', { shortURL, fullURL: URL_obj.fullURL })

Please let me know if this works as I can hardly test it :)

  • Related