Reputation: 1171
I would like to create auto increment ID with Mongoose for MongoDB. I was already looking for some examples, but there aren't anything useful other the MongoDB's documentation.
Upvotes: 10
Views: 18653
Reputation: 6564
Use mongoose-sequence, For eg: In the below model, it increments order number by one when a new document is inserted.
const mongoose = require('mongoose'),
Schema = mongoose.Schema;
const AutoIncrement = require('mongoose-sequence')(mongoose);
const orderSchema = new Schema({
_id: mongoose.Schema.Types.ObjectId,
orderId: {
type: Number
}
...
});
orderSchema.plugin(AutoIncrement, {inc_field: 'orderId'});
module.exports = mongoose.model('Order', orderSchema);
There is an important thing that needs to be understood. If you add required: true in the schema, the operation breaks.
In your route file, you can create a mongoose order object and call save.
...
const order = new Order(body);
order.save()
.then(doc => {
res.json(doc);
res.end();
});
Upvotes: 6
Reputation: 930
On npm we have mongoose-auto-increment and mongoose-sequence packages to achieve this functionality very easily.
Upvotes: 5