[SETTLED] Auto-increment an id in mongoose

[SETTLED] Auto-increment an id in mongoose
0

#1

How do you auto-increment an id in a mongoose schema? I can’t seem to find it in the docs. It’s possible to auto-increment a primary key in MySQL, and I’m wondering if the same can be done with mongoose.


#2

If you leave the “_id” field out of the model and any subsequent inserts, Mongo/mongoose generate a unique ID for you. You don’t have to manage it yourself or auto-increment it.


#3

This is for the URL shortener, and I plan to use the _id field to contain the shortened URL (the default IDs are too long for this purpose!).

On a side note, the notifications really are broken.


#4

Theoretically, IDs should only serve the purpose of being an ID. When you start giving things (especially important things like unique IDs) multiple purposes, things can get messy.

Why not have this structure:

{
    "_id": {
        "$oid": "blahmessyhexstring"
    },
    "orig_url": "http://something.com",
    "short_url": "http://shorty.com/1"
}

#5

Well, the idea is that shortened URLs are supposed to be unique, so I thought they qualify as values for _id. but I guess I’ll take your advice and generate the shortened URLs myself.


#6

@kevcomedia If you want to replicate the freeCodeCamp project what you can do is use mongoose estimatedDocumentCount() that will give the number of documents in your DB. You can use that as the short_url since you are not gonna be deleting any data on your database so the number won’t decrease.