Plugin for generating sequential field values. It adds a pre('save') hook to the attached schema and some useful static methods.

Basic usage example

const Generator = require ( ' @alonsojr1980/mongoose-generator ' ) ; const mongoose = require ( ' mongoose ' ) ; const UserSchema = new mongoose . Schema ( { name : String , age : Number } ) ; const nameOfTheGenerator = ' users ' ; UserSchema . plugin ( Generator , nameOfTheGenerator ) ; const model = mongoose . model ( ' User ' , UserSchema ) ; const user1 = model ( { name : " ALONSO " } ) ; user1 . save ( ( ) => { console . log ( user1 . _id ) ; } ) ;

The following document will be added to a collection named generators: {"name": "users", "sequence": 1}

Default plugin options

const pluginOptions = { collection : " generators " , name : undefined , startAt : 100 , increment : 1 , field : " _id " }

Custom options example

const BusSchema = new mongoose . Schema ( { sequentialNumber : Number , licensePlate : String } ) ; const pluginOptions = { collection : " generators " , name : " buses " , startAt : 100 , increment : 1 , field : " sequentialNumber " } BusSchema . plugin ( Generator , pluginOptions ) ; const model = mongoose . model ( ' Bus ' , BusSchema ) ; const bus1 = model ( { licensePlate : " BUS-7777 " } ) ; bus1 . save ( ( ) => { console . log ( bus1 . sequentialNumber ) ; } ) ;

The following document will be added to a collection named generators:

{"name": "buses", "sequence": 101}

Static methods added to the model

currentSequence ( ( err , sequence ) => { } ) ; gen_id_reset ( ( err , sequence ) => { } )

Remember that static methods are called in the model, not in the document instance.

Static methods usage example