npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

mongoose-auto-increment-reworked

v1.2.1

Published

An auto-incrementing field generator for Mongoose 4 & 5

Downloads

945

Readme

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