1

When adding a field called date in mongo db, I can do just:

date: {
    type: Date,
    default: Date.now
}

and it will automatically add date field to my new collection when it was created. Is there some way to add a self-incrementing index (id) to my collections?

Note: I tried to do it on client side, however with every time I push collection with (id) field, its being deleted from the collection and replaced with _id which is a long string with random characters. Way to long!

Looking for every hints.

Edit: code responsible for adding use to db

app.post("/users", function (req, res) {
    createUser(req.body, function (err, user) {
        if (err) {
            return res.json(err);
        }
        return res.json(user);
    });
});
Patrickkx
  • 1,740
  • 7
  • 31
  • 60

2 Answers2

2

MongoDB automatically makes unique ids for each object in the database, resulting in each entry having a unique _id field being an ObjectId. You don't really need to worry about specifying custom ids.

You can sort by _id if you want objects roughly in the order they were created, or you could add a date field which is set on creation and sort by that.

Other than that, I'm not sure what you'd gain by having auto incrementing ids

sbrass
  • 905
  • 7
  • 12
  • But I dont want to use that long id in path. Im using a path: `/user/:id`. It will be ridiculous if I'd use it and it would result in a link: `mydomain.com/user/13k4r3f329d3dk`. Looks weird, right? But if it would be something which increments from 0, would be `mydomain.com/user/1`. Looks better, right? – Patrickkx Aug 15 '18 at 22:03
  • 3
    @Patrickkx: "looks better, right?" - it's not like you'll be typing out these urls by hand (or memorizing them), so it's not clear why would you care too much about this? ¯\\_(ツ)_/¯ Some browsers won't even show that part of the address. Plus, mongodb has a very good reason to use ObjectId as default id type: it is very hard to maintain auto-incrementing sequence in a distributed db. – Sergio Tulentsev Aug 15 '18 at 22:12
1

There are multiple ways to implement an auto-increment index but it is not considered a good practice.

Detailed information here: Auto increment in MongoDB to store sequence of Unique User ID

Check Rizwan Siddiquee answer about how to implement it with a stored javascript function.

Another way would be to implement it on application layer using any kind of ODM but this is obviously dangerous and not so trustable for serious applications.

manuelbcd
  • 3,106
  • 1
  • 26
  • 39