Mongoose plugin that auto-increment any field on your schema that you wish. Also supports suffix & prefix.
npm install mongoose-super-increment





> Mongoose plugin that auto-increments any ID field on your schema every time a document is saved.

1. Installation
2. Usage
3. API
4. License
``sh`
npm install mongoose-super-increment -S
Initialize Mongoose Super Increment and add plugin to a schema.
> Note: You only need to initialize Mongoose Super Increment only once.
`js
const mongoose = require('mongoose');
const mongooseSuperIncrement = require('mongoose-super-increment');
const connection = mongoose.connect();
mongooseSuperIncrement.initialize(connection);
const bookSchema = new Schema({
author: { type: Schema.Types.ObjectId, ref: 'Author' },
title: String,
genre: String,
publishDate: Date
});
bookSchema.plugin(mongooseSuperIncrement.plugin, { model: 'Book' });
module.exports = mongoose.model('Book', bookSchema);
`
That's it. Now you can create book entities at will and they will have an no field added of type String and will automatically increment with each new document.
``js``
bookSchema.plugin(mongooseSuperIncrement.plugin,
{
model: 'Book',
field: 'bookId'
});
``js``
bookSchema.plugin(mongooseSuperIncrement.plugin, {
model: 'Book',
field: 'bookId',
startAt: 100,
incrementBy: 100
});
Your first book document would have a bookId equal to 100. Your second book document would have a bookId equal to 200, and so on.
``js``
bookSchema.plugin(mongooseSuperIncrement.plugin, {
model: 'Book',
field: 'bookId',
startAt: 100,
incrementBy: 100,
prefix: 'Book-',
suffix: (doc) => {
// Process the doc being which is being saved.
return 'Book-';
},
});
`js`
MongooseSuperIncrement.initialize([connection]);
Parameters
* [connection] {Object} Mongoose Connection (required)
`js`
Model.plugin(MongooseSuperIncrement.plugin, [options]);
Parameters
* [options] {Object} (required)model
- {String} Mongoose model name (required)field
- {String} Mongoose increment field name (optional, default value is no)startAt
- {Number} Mongoose increment field name (optional, default value is 0)incrementBy
- {Number} Number to increment counter (optional, default value is 1)prefix
- {String/Function} Counter Prefix (optional, default value is an empty string)suffix` {String/Function} Counter Suffix (optional, default value is an empty string)
-