10

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.

user1257255
  • 1,161
  • 8
  • 26
  • 55

2 Answers2

6

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();
     });
Anees Hameed
  • 5,916
  • 1
  • 39
  • 43
5

On npm we have mongoose-auto-increment and mongoose-sequence packages to achieve this functionality very easily.

ShrekOverflow
  • 6,795
  • 3
  • 37
  • 48
Shubham Jain
  • 930
  • 1
  • 14
  • 24
  • 1
    `mongoose-sequence` is the way to go from what I saw - thank you. `mongoose-auto-increment` uses deprecated functions and wasn't updated since 2016 (abandoned?) - let's blame https://github.com/chevex. – Fusseldieb Nov 05 '18 at 16:28