[英]Mongoose create document if doesn't exist
我正在制作一個簡單的網址縮短器(Mong db,Node js)。 這是我的模型:
var urlSchema = new mongoose.Schema({
shortUrl: String,
longUrl: String,
created: {
type: Date, default: Date.now
},
clicks: {
type: Number, default: 0
}
});
我有一個函數getRandomString6()返回6個隨機字符串。
var string = getRandomString6();
我想實現這種“偽代碼”算法:
1 var string = getRandomString6();
2 if there is document with shortUrl == string
3 go to step 1
4 else
5 create new document with shortUrl=string
怎么做?
這很容易實現,該示例應有助於獲得想法
function getValidShortUrl(cb) {
var str = getRandomString6();
MODEL.findOne({
shortUrl: str
}, function(err, doc) {
if(err) return cb(err);
else if (doc) return getValidShortUrl(cb);
else cb(null, str);
});
}
getValidShortUrl(function(err, shortUrl) {
if(err) {
// error
} else {
// shortUrl is valid url that doesn't exist in schema
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.