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;
}
}