how can I create a auto-increment field in mongoose how can I create a auto-increment field in mongoose mongoose mongoose

how can I create a auto-increment field in mongoose


there is a very simple and easy way to implement auto increment in mongoose by using mongoose pre save function. Here are my codes for user collection, try the same trick in your mongoose model(schema) to implement auto increment. Paste this code in your collection schema file and replace some variables(userSchema, user) according to your collection schema.

userSchema.pre('save', function(next) {    var currentDate = new Date();    this.updated_at = currentDate;    if (!this.created_at)        this.created_at = currentDate;    var sno = 1;    var user = this;    User.find({}, function(err, users) {    if (err) throw err;        sno = users.length + 1;        user.sno = sno;        next();    });});


If you are using soft delete functionality above answer may work but to solve it, there are several ways.1: Before inserting a new record fetch the last document(row) and put id = 1 + (id of the last record).2: You can use plugin mongoose-auto-increment.3: Last but not least option save the last incremented value in a separate collection(collection name: autoIncrement columns will be collection and sno), before creating a record fetch the sno value of that collection increment it, create your record and update the sno value again in autoIncrement collection.

Bonus:

1: You can create autoIncrement in redis.

2: The first point of this answer will not able to solve several problems, ie: Your app will do kind of behavior on deletion, if user delete a row from start or middle of your collection, it will remove that id(that sno. form table), but in case the user deletes the last record. It will put that sno. in next record.

var CounterSchema = Schema({    _id: {type: String, required: true},    seq: { type: Number, default: 0 }});var counter = mongoose.model('counter', CounterSchema);var entitySchema = mongoose.Schema({    testvalue: {type: String}});entitySchema.pre('save', function(next) {    var doc = this;    counter.findByIdAndUpdate({_id: 'entityId'}, {$inc: { seq: 1} }, function(error, counter)   {        if(error)            return next(error);        doc.testvalue = counter.seq;        next();    });});