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
- Getting the next ID
- Resetting the ID to its starting value
- Configuration
- Getting initialisation information
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.
;; const MySchema = 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; const plugin = MySchema 'MyModel'; plugin ; /* * 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; // 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;
Getting the next ID
MyModel ;
Resetting the ID to its starting value
MyModel ;
Configuration
The plugin's configuration accepts the following options:
/** Plugin configuration */
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; MySchema 'MyModel' options;
Default configuration
You can get the current default configuration as follows:
MongooseAutoIncrementID;
And set it as follows:
MongooseAutoIncrementID;
Getting initialisation information
You can get the current initialisation state of the plugin via instance methods:
const mySchema = /*...*/;const plugin = mySchema 'MyModel';const promise = plugin; console; // trueconsole;console;
Or via static methods:
MongooseAutoIncrementID;MongooseAutoIncrementID;MongooseAutoIncrementID;