Skip to content

Instantly share code, notes, and snippets.

@ivanvmoreno
Created December 9, 2019 12:43
Show Gist options
  • Save ivanvmoreno/bb97d13d04a201bdce9cda9019e1dbf8 to your computer and use it in GitHub Desktop.
Save ivanvmoreno/bb97d13d04a201bdce9cda9019e1dbf8 to your computer and use it in GitHub Desktop.
mongoose auto-increment field on creation with middleware
const mongoose = require('mongoose')
const testSchema = new mongoose.Schema({
id: {
type: Number,
unique: true,
required: true,
min: 1,
},
})
const testModel = mongoose.Model('Test', testSchema)
// Middleware to enforce auto-increment of Test.id
testSchema.pre('save', async next => {
if (this.isNew) {
this.id = await testModel.count()
} else {
next()
}
})
module.exports = testModel
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment