我正在制作一个URL缩短器,需要判断生成的短URL是否在数据库中不存在,以避免数据损坏.
我正在mongodb和mongoose中使用node和express.这是我提出的算法,但我真的不喜欢它.我有没有办法用更干净的方式来做这件事?
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;
}
}
欢迎任何其他批评/意见!