简体   繁体   English

猫鼬创建文档(如果不存在)

[英]Mongoose create document if doesn't exist

I am making a simple url shortener(Mong db, Node js). 我正在制作一个简单的网址缩短器(Mong db,Node js)。 Here is my model: 这是我的模型:

var urlSchema = new mongoose.Schema({
    shortUrl: String,
    longUrl: String,
    created: {
        type: Date, default: Date.now
    },
    clicks: {
        type: Number, default: 0
    }
});

I have a function getRandomString6() that returns 6 random characters string. 我有一个函数getRandomString6()返回6个随机字符串。

var string = getRandomString6();

I want to implement this "pseudocode" algorithm: 我想实现这种“伪代码”算法:

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

How to do that? 怎么做?

It's pretty easy to achieve, this sample should help to get idea 这很容易实现,该示例应有助于获得想法

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM