1.1.0 • Published 5 years ago
mongoose-super-increment v1.1.0
mongoose-super-increment
Mongoose plugin that auto-increments any ID field on your schema every time a document is saved.
Table of Contents
Installation
npm install mongoose-super-increment -SUsage
Initialize Mongoose Super Increment and add plugin to a schema.
Note: You only need to initialize Mongoose Super Increment only once.
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.
Want a field other than no?
bookSchema.plugin(mongooseSuperIncrement.plugin,
{
model: 'Book',
field: 'bookId'
});Want that field to start at a different number than zero or increment by more than one?
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.
Want to use suffix or prefix?
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-';
},
});API
Initialize
MongooseSuperIncrement.initialize([connection]);Parameters
[connection]{Object} Mongoose Connection (required)
Plugin
Model.plugin(MongooseSuperIncrement.plugin, [options]);Parameters
[options]{Object} (required)model{String} Mongoose model name (required)field{String} Mongoose increment field name (optional, default value isno)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)
