mongoose-counters
This plugin create fields which autoincrement their value every time a new document is inserted in a collection.
Installation
yarn add mongoose-countersnpm i mongoose-counters
Setup
This plugin accept a series of options.
- id: Id of the counter. Is mandatory only for scoped counters but its use is strongly encouraged.
- incField: The name of the field to increment. Mandatory, default is
_id
- referenceFields: The field to reference for a scoped counter. Optional
- collectionName: The collection name to mantain the status of the counters. Mandatory, default is
counters
Use as you would any Mongoose plugin:
;; ;;schema.plugincounter, ;;
The increment can be:
global
: every document has a unique value for the counter fieldscoped
: the counter depends on the value of other field(s)
Global counters
Let's say you want to have an id
field in your collection
which has an unique auto-incremented value.
The model schema is something like this:
ModelSchema = mongoose.Schema; mongoose.model'ModelName', ModelSchema;
You don't need to define the id
field in your schema because the plugin automatically set it for you. The only thing you have to do is to call:
ModelSchema.plugincounter, ;
Every time a new model entry is created, the id
field will have an incremental number.
If you want to increment the _id
field which is special to mongoose, you have to explicitly specify it as a Number and tell mongoose to not interfer:
ModelSchema = mongoose.Schema, ;ModelSchema.pluginAutoIncrement;
In this case you don't have to specify incField
because the default value is _id
Scoped counters
Let say our users are organized for country
and city
. And we want to save the inhabitant_number
according to the two informations.
The schema is like this:
UserSchema = mongoose.Schema;
Every time a new Parisian is added the counting of Parisians have to be incremented. The inhabitants of New York must not interfer and have their separated counting. We should define a scoped counter which increment the counter depending on the value of other fields.
UserSchema.pluginAutoIncrement, ;
Notice that we have to use an id for our sequence, otherwise the plugin will raise an error.
API
resetCounter()
It's possible to programmatically reset a counter through the Model static method counterReset(id, reference, callback)
. The method take those parameters:
- id: the counter to reset. It's mandatory
- reference: Let you reset only a specific reference of the counter, if the counter has referenced fields. Optional. By default it reset all the counters for the
id
- callback: A callback which receive an error in case of any. Mandatory
Model; Model;
Credits
This plugin is inspired by ramiel/mongoose-sequence.