简体   繁体   中英

Incrementing index in mongo db

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);
    });
});

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM