- fix error
'required' is not valid for an index specificationfor Mongoose 4
- does not require established connection for initialization (deprecate
- include Flowtype and Typescript declarations
- tested with Mongoose 5
- setup automatic package publishing on PR merge with Travis CI and sematic-release
npm install mongoose-plugin-autoinc
Once you have the plugin installed it is very simple to use. Just pass
autoIncrement to the
plugin() function on your schema.
Note: You only need to initialize MAI once.
;;const connection = mongoose;const BookSchema =author: type: SchemaTypesObjectId ref: 'Author'title: Stringgenre: StringpublishDate: Date;BookSchema;const Book = connection;
That's it. Now you can create book entities at will and they will have an
_id field added of type
Number and will automatically increment with each new document. Even declaring references is easy, just remember to change the reference property's type to
Number instead of
ObjectId if the referenced model is also using the plugin.
const AuthorSchema =name: String;const BookSchema =author: type: Number ref: 'Author'title: Stringgenre: StringpublishDate: Date;BookSchema;AuthorSchema;
Want a field other than
Want that field to start at a different number than zero or increment by more than one?
Your first book document would have a
bookId equal to
100. Your second book document would have a
bookId equal to
200, and so on.
Want to know the next number coming up?
const Book = connection;Book;
nextCount is both a static method on the model (
Book.nextCount(...)) and an instance method on the document (
Want to reset counter back to the start value?
BookSchema;const Book = connectionbook = ;book;