Search code examples
mongodbmongooseauto-increment

How to concurrently increment a 5 digit counter starting with 00000 in mongoose


I want to create an accession no. field in mongodb which starts from 00000 (5 digits) and then increment the 5 digit number by 1 everytime a book is added.


Solution

  • This will depend on the use case, but i would recommend just using an normal number in the database and then before returning it to where the padded number is needed, to pad it to the wanted digits.

    This can also be easily done with the set & get options inside mongoose.
    As for the auto-increment, i would recommend to use mongoose-auto-increment or @typegoose/auto-increment. (choose what best suits your needs)

    PS: if this approach is not wanted, the only other option would be to store that number as an string or buffer inside the database, which would be inefficient.