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 | const Schema = mongoose.Schema; |
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.