I’m working on the URL Shortener API project by freeCodeCamp. To get a robustly unique auto-increment shortened URL, I want to implement auto-increment at MongoDB.

My implementation could be find at this GitHub repository.

What the data structure looks like

The UrlPair is the model to store the pairing between original URL and the short URL.
The Counter is the model to keep track of auto-incrementation. Each counter has a for value stating what it is counting for.

1
2
3
4
5
6
7
8
9
10
11
const Schema = mongoose.Schema;
const urlPairSchema = new Schema({
"original": {type: String, required: true},
"short": {type: String, required: true, unique: true}
});
const UrlPair = mongoose.model("URL_Pair", urlPairSchema);
const counterSchema = new Schema({
"for": {type: String, required: true, unique: true},
"counter": {type: Number, default: 0, required: true}
});
const Counter = mongoose.model("Counter", counterSchema);

How to achieve incrementation

The query looks as follows:

1
Counter.findOneAndUpdate({"for": "URL_Pair"}, {$inc: {"counter": 1}}, {upsert: true})

findOneAndUpdate takes three argument, the condition, the update and the options (and then the callback).
$inc is the query to increment the specified value.

How to insert the initial doc

{upsert:true} option instructs findOneAndUpdate to insert a new doc if the queried doc does not exist.