Mongoose auto increment Mongoose auto increment mongoose mongoose

Mongoose auto increment


Here is an example how you can implement auto-increment field in Mongoose:

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


You can use mongoose-auto-increment package as follows:

var mongoose      = require('mongoose');var autoIncrement = require('mongoose-auto-increment');/* connect to your database here *//* define your CounterSchema here */autoIncrement.initialize(mongoose.connection);CounterSchema.plugin(autoIncrement.plugin, 'Counter');var Counter = mongoose.model('Counter', CounterSchema);

You only need to initialize the autoIncrement once.


The most voted answer doesn't work. This is the fix:

var CounterSchema = new mongoose.Schema({    _id: {type: String, required: true},    seq: { type: Number, default: 0 }});var counter = mongoose.model('counter', CounterSchema);var entitySchema = mongoose.Schema({    sort: {type: String}});entitySchema.pre('save', function(next) {    var doc = this;    counter.findByIdAndUpdateAsync({_id: 'entityId'}, {$inc: { seq: 1} }, {new: true, upsert: true}).then(function(count) {        console.log("...count: "+JSON.stringify(count));        doc.sort = count.seq;        next();    })    .catch(function(error) {        console.error("counter error-> : "+error);        throw error;    });});

The options parameters gives you the result of the update and it creates a new document if it doesn't exist.You can check here the official doc.

And if you need a sorted index check this doc