Created
December 9, 2019 12:43
-
-
Save ivanvmoreno/bb97d13d04a201bdce9cda9019e1dbf8 to your computer and use it in GitHub Desktop.
mongoose auto-increment field on creation with middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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