There is plenty of stack overflow posts about how to create an auto-increment field in mongoose.
auto-increment-document-number-in-mongo-mongoose
create-unique-autoincrement-field-with-mongoose
@edtech
Here is a good example of auto-incremented fields implementation using 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 should perform the Step 1 from mongodb documentation firstly.
EDIT - Soluce without mongoose - Aka MongoDB Native Driver
You can use the mongodb native node.js driver and implements one of the soluce explained in theses stack overflow posts:
auto-increment-in-node-mongodb-native-using-counters-collection
Creating incrementing numbers with mongoDB