Skip to content

Instantly share code, notes, and snippets.

@but1head
Last active September 22, 2020 13:05
Show Gist options
  • Save but1head/bf0eea77801c4d758f268ed9eaab070f to your computer and use it in GitHub Desktop.
Save but1head/bf0eea77801c4d758f268ed9eaab070f to your computer and use it in GitHub Desktop.
Mongoose / mongo short integer id
// 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