[SETTLED] Auto-increment an id in mongoose

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.

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.

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.

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"
}
1 Like

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.

@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.

1 Like