0

I am making a simple url shortener(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.

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?

kurumkan
  • 2,635
  • 3
  • 31
  • 55
  • Possible duplicate of [Mongoose - Create document if not exists, otherwise, update- return document in either case](http://stackoverflow.com/questions/33305623/mongoose-create-document-if-not-exists-otherwise-update-return-document-in) – Bertrand Martel Oct 31 '16 at 16:39
  • @BertrandMartel In my case the document must be created in any case. Not just skip if it exists and not update. – kurumkan Oct 31 '16 at 16:49

1 Answers1

0

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
    }
});
Medet Tleukabiluly
  • 11,662
  • 3
  • 34
  • 69