// 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