You can use this plugin: https://www.npmjs.com/package/mongoose-auto-increment
First you need to initialize it after creating Mongoose connection:
const connection = mongoose.createConnection("mongodb://localhost/myDatabase");
autoIncrement.initialize(connection);
Than in your subs.model.js file:
const mongoose = require('mongoose');
const autoIncrement = require('mongoose-auto-increment');
var subscriberSchema = new mongoose.Schema({
_id: {type: String, required: true},
email: {
type: String
}
}, {
versionKey: false,
collection: 'subscribers'
});
subscriberSchema.plugin(autoIncrement.plugin, {
model: 'Subscribers',
field: '_id'
});
module.exports = mongoose.model('Subscribers', subscriberSchema);
// schema creation...
let modal;
SchemaVariable.pre('save', function(next) {
if (this.isNew) {
if (!modal) {
modal = mongoose.model('collectionname');
}
modal.find({})
.then((entries) => {
this._id = entries.length + 1;
next();
})
}
});
// using pre('save' on your mongoose schema
// creating the counter collection/model to save the number of documents:
const counterCollection = mongoose.model('counter',
new mongoose.Schema({number: Number}), 'counter')
// updating the counter and the pre-saved document that need the index/number
documentSchema.pre('save', async function() {
if(this.number) {
let counterDoc = await counterCollection.findOne()
if(!counterDoc) {
counterDoc = new counterCollection({number: 1})
} else {
counterDoc.number++
}
this.number = counterDoc.number
const response = await counterDoc.save()
}
})
// don't forget to update the schema with the number key-value pair to
// store the number, so mongoose does not throw error