Last active
September 22, 2020 13:05
-
-
Save but1head/bf0eea77801c4d758f268ed9eaab070f to your computer and use it in GitHub Desktop.
Mongoose / mongo short integer id
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
// counter collection | |
const Counter = new Schema({ | |
value: { type: Number, default: 0 }, | |
model: { type: String, required: true }, | |
}, { | |
timestamps: false, | |
versionKey: false, | |
}); | |
// increment function | |
export const MongooseIncrement = async (model) => { | |
const tmp = await Counter.findOneAndUpdate( | |
{ model }, | |
{ | |
$inc: { value: 1 } | |
}, | |
{ | |
new: true, | |
upsert: true, | |
}); | |
return tmp.value; | |
} | |
// model hook | |
Order.pre('save', function (next) { | |
if(!this.isNew) return next(); | |
const instance = this; | |
MongooseIncrement('Order').then(value => { | |
instance.shortId = value; | |
next(); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment