How to create field that will auto increment after insertion of new record in MongoDB?
I'm using Mongoose and Node.js
The Schema of the model is as follows:
let orderSchema = new Schema({
'product': String,
'orderNumber': Number,
'totalPrice': Number,
'customer': {
'type': Schema.Types.ObjectId,
'ref': 'Users'
});
I want to set the orderNumber
as an incrementing integer.
Is there any way to do it in MongoDB?
I don't want to use the pre-hook technique to do it
Solution 1:
You need to create a collection with counters and a plugin with two hooks inside:
-
schema.pre
- to get the current value of counter -
schema.post
- to save new value of counter
Counter schema will look like this:
const conterSchema = new Schema({
name: String,
value: Number
});
While the plugin will can be defined like this:
function incrementOrderNumber (schema) {
schema.pre('save', next => {
CounterModel.findOne({ name: 'orderNumberCounter' })
.then(counterDoc => counterDoc.toObject())
.then(({ value}) => {
this.orderNumber = value;
next();
});
});
schema.post('save', next => {
CounterModel.findOneAndUpdate({ name: 'orderNumberCounter' }, { $inc: { value: 1 }}).exec();
});
}
After creating such plugin function you will need to plug it into your schema:
orderSchema.plugin(incrementOrderNumber);
Do not forget to insert orderNumberCounter
into counters
collection.