Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I create a auto-increment field in mongoose

can any one tell me how can I create a auto-increment field in mongoose without using any library or plugin. Any simple and easy way..

like image 880
lakshmankashyap Avatar asked Sep 03 '25 08:09

lakshmankashyap


1 Answers

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();
    });
});
like image 173
Utkarsh Pandey Avatar answered Sep 04 '25 23:09

Utkarsh Pandey