Skip to content
This repository has been archived by the owner on Jul 8, 2019. It is now read-only.

Alorel/mongoose-auto-increment-reworked

Repository files navigation

NPM link

Build Status Coverage Status Greenkeeper badge Supports Node >= 6

A rewrite of mongoose-auto-increment with optimisations and tests updated for the latest versions of Mongoose 4 and 5, as well as new features.


Table of Contents

Basic usage

The plugin creates a pre-save middleware on the provided schema which generates an auto-incrementing ID, therefore it must be applied before your schema gets turned into a model.

import {MongooseAutoIncrementID} from 'mongoose-auto-increment-reworked';
import * as mongoose from 'mongoose';

const MySchema = new mongoose.Schema({
  someField: {
    type: String
  }
});

/*
 * An optional step - set the name of the schema used by the plugin (defaults to 'IdCounter'). Has no effect if
 * the plugin has already been applied to a schema.
 */
MongooseAutoIncrementID.initialise('MyCustomName');

const plugin = new MongooseAutoIncrementID(MySchema, 'MyModel');

plugin.applyPlugin()
  .then(() => {
    // Plugin ready to use! You don't need to wait for this promise - any save queries will just get queued.
    // Every document will have an auto-incremented number value on _id.
  })
  .catch(e => {
    // Plugin failed to initialise
  });

/*
 * Alternatively, just use schema.plugin(). The options passed MUST contain the "modelName" key and, optionally,
 * any of the parameters from the configuration section below.
 */
MySchema.plugin(MongooseAutoIncrementID.plugin, {modelName: 'MyModel'});

// Only turn the schema into the model AFTER applyPlugin has been called. You do not need to wait for the promise to resolve.
const MyModel = mongoose.model('MyModel', MySchema);

Getting the next ID

MyModel._nextCount()
  .then(count => console.log(`The next ID will be ${count}`));

Resetting the ID to its starting value

MyModel._resetCount()
  .then(val => console.log(`The counter was reset to ${val}`));

Configuration

The plugin's configuration accepts the following options:

/** Plugin configuration */
export interface PluginOptions {
  /**
   * The field that will be automatically incremented. Do not define this in your schema.
   * @default _id
   */
  field: string;
  /**
   * How much every insert should increment the counter by
   * @default 1
   */
  incrementBy: number;
  /**
   * The name of the function for getting the next ID number.
   * Set this to false to prevent the function from being added to the schema's static and instance methods.
   * @default _nextCount
   */
  nextCount: string | false;
  /**
   * The name of the function for resetting the ID number
   * Set this to false to prevent the function from being added to the schema's static and instance methods.
   * @default _resetCount
   */
  resetCount: string | false;
  /**
   * The first number that will be generated
   * @default 1
   */
  startAt: number;
  /**
   * Whether or not to add a unique index on the field. This option is ignored if the field name is _id.
   * @default true
   */
  unique: boolean;
}

You can pass them as the third parameter to the plugin's constructor:

const options = {
  field: 'user_id', // user_id will have an auto-incrementing value
  incrementBy: 2, // incremented by 2 every time
  nextCount: false, // Not interested in getting the next count - don't add it to the model
  resetCount: 'reset', // The model and each document can now reset the counter via the reset() method
  startAt: 1000, // Start the counter at 1000
  unique: false // Don't add a unique index
};

new MongooseAutoIncrementID(MySchema, 'MyModel', options);

Default configuration

You can get the current default configuration as follows:

MongooseAutoIncrementID.getDefaults();

And set it as follows:

MongooseAutoIncrementID.setDefaults(myNewDefaults);

Getting initialisation information

You can get the current initialisation state of the plugin via instance methods:

const mySchema = new mongoose.Schema({/*...*/});
const plugin = new MongooseAutoIncrementID(mySchema, 'MyModel');
const promise = plugin.applyPlugin();

console.log(plugin.promise === promise); // true
console.log(`Plugin ready: ${plugin.isReady}`);
console.log('Initialisation error: ', plugin.error);

Or via static methods:

MongooseAutoIncrementID.getPromiseFor(mySchema, 'MyModel');
MongooseAutoIncrementID.isReady(mySchema, 'MyModel');
MongooseAutoIncrementID.getErrorFor(mySchema, 'MyModel');