26

Given a Schema:

var EventSchema = new Schema({
    id: {
        // ...
    },
    name: {
        type: String
    },
});

I want to make id unique and autoincrement. I try to realize mongodb implementation but have problems of understanding how to do it right in mongoose.

My question is: what is the right way to implement autoincrement field in mongoose without using any plugins and so on?

Community
  • 1
  • 1
Boris Zagoruiko
  • 12,705
  • 15
  • 47
  • 79

4 Answers4

5
const ModelIncrementSchema = new Schema({
    model: { type: String, required: true, index: { unique: true } },
    idx: { type: Number, default: 0 }
});

ModelIncrementSchema.statics.getNextId = async function(modelName, callback) {
    let incr = await this.findOne({ model: modelName });

    if (!incr) incr = await new this({ model: modelName }).save();
    incr.idx++;
    incr.save();
    return incr.idx;
};


const PageSchema = new Schema({
    id: { type: Number ,  default: 0},
    title: { type: String },
    description: { type: String }
});


PageSchema.pre('save', async function(next) {
    if (this.isNew) {
        const id = await ModelIncrement.getNextId('Page');
        this.id = id; // Incremented
        next();
    } else {
        next();
    }
});
Natali
  • 57
  • 1
  • 2
  • 3
    [Code-only answers](https://meta.stackoverflow.com/questions/300837/what-comment-should-i-add-to-code-only-answers) can be improved by explaining how the code works! – Dan Dascalescu Apr 15 '20 at 00:18
1

Yes, here's the "skinny" on that feature.

You need to have that collection in your mongo database. It acts as concurrent key allocation single record of truth if you want. Mongo's example shows you how to perform an "atomic" operation to get the next key and ensure that even there are concurrent requests you will be guaranteed to have the unique key returned without collisions.

But, mongodb doesn't implement that mechanism natively, they show you how to do it. They only provide for the _id to be used as unique document key. I hope this clarifies your approach.

To expand on the idea, go ahead and add that mongo suggested implementation to your defined Mongoose model and as you already guessed, use it in Pre-save or better yet pre-init event to ensure you always generate an id if you work with a collection server side before you save it to mongo.

Biba
  • 748
  • 4
  • 13
-1

You can use this. This package every time generate unique value for this.

Package Name : uniqid

Link : https://www.npmjs.com/package/uniqid

Dhaval Mojidra
  • 194
  • 1
  • 2
  • 11
  • 1
    What's the point of using that instead of Mongo's native ObjectId? That package also generates a long identifier, and the OP presumably wants something short and readable, or else they'd use ObjectId, which is also always-incrementing, just not by 1. – Dan Dascalescu Apr 15 '20 at 00:16
-5

Ignore all the above. Here is the solution

YourModelname.find().count(function(err, count){
   req["body"].yourID= count + 1;
      YourModelname.create(req.body, function (err, post) {
        if (err) return next(err);
        res.json(req.body);
      });
    });
  • 3
    Actually this is a bad approach and should be ignored, the type of operation he requests needs to be atomic. In case of concurrent requests, you can easily get the same id twice. – naor.z Oct 07 '19 at 08:57
  • 1
    Yeah! This is not a solution for production-ready apps. – Prathamesh More Jan 05 '20 at 08:08
  • the operation you suggested may go unattended if server stress is high ... the operation is a macromolecule and not atomic – Aloy A Sen Apr 04 '20 at 05:02