ArslArsl ArslArsl - 1 year ago 187
Node.js Question

Mongoose create document if doesn't exist

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:
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?

Answer Source

It's pretty easy to achieve, this sample should help to get idea

function getValidShortUrl(cb) {
    var str = getRandomString6();
        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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download