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

Viewed 55

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.js 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;
    }
}
1 Answers

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

let shortURLstr

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

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

res.render('shortenedURL', { shortURL: req.get('host') + "/" + shortURL, fullURL })
Related