0

I want to implement auto increase id for procedureid & doctorId in the below schema and id should be a 5 digit number. What is the best way to do it.Can some one give a sample code

var hospitalDoctorSchema = new Schema({

    Treatment: [{
            procedureid: {
                type: Number,
                required: true,
                unique: true,
                default: 0
            },

            doctor: {
                doctorId: {
                    type: Number,
                    required: true,
                    unique: true,
                    dropDups: true,
                    default: 0
                }],

        },
    },
    updated_at: {
        type: Date,
        required: true,
        default: Date.now
    }
});
Talha Awan
  • 4,573
  • 4
  • 25
  • 40
Sona Shetty
  • 997
  • 3
  • 18
  • 41

1 Answers1

0

Update : I made a change so read this again carefully.

I know a work around for what you're trying to accomplish. If all you want is a number to keep track of things and want it to be unique, you can use the Unix time stamp to accomplish this.

Set the default value of procedureid like this :

default : new date().getTime()

getTime is a function which returns the number of milliseconds passed since 1970 Jan 1, so every id you generate is unique and greater than the previous one.

So you get a 13 digit number which is big but unique for up to 1000 inserts per second to your db!!

If you think 13 is a too much, you can bring this down to 9 but with characters included with a few more lines of code.

First install hashids from npm .

npm install hashids --save

Now add this to your file.

const hash = require("hashids");
var new_hash = new hash("A salt");
var unique_number  = new Date().getTime();
var unique_id = new_hash.encode(unique_number); // This is the unique id with chars included.

You can now use the unique_id where ever you want, but don't change the salt once you deployed your app to avoid collisions.

Shiva Teja
  • 417
  • 4
  • 16