mongoose-super-increment

1.1.0 • Public • Published

mongoose-super-increment

npm version Dependency Status devDependency Status contributions welcome Downloads Github

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

NPM

Table of Contents

  1. Installation
  2. Usage
  3. API
  4. License

Installation

npm install mongoose-super-increment -S

Usage

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 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)

License

MIT

Readme

Keywords

none

Package Sidebar

Install

npm i mongoose-super-increment

Weekly Downloads

68

Version

1.1.0

License

MIT

Unpacked Size

10.1 kB

Total Files

5

Last publish

Collaborators

  • hariaakash