mongodb-autoincrement
=====================
Module to auto increment mongodb _id index. There is also mongoose plugin here.
Installing
npm install mongodb-autoincrement
Using
...with mongodb-native driver
Gets next auto increment integer index from database for the given collection. The successive calls to this function return different values so you can safely use it in multi client applications.
getNextSequence(db, collectionName, fieldName, callback)
- db - mongodb-native driver connection object
- collectionName - name of the collection to get auto increment index for, string
- fieldName - name of the auto increment field [optional]
- callback - function (err, nextFreeIndex)
var MongoClient = MongoClient;var autoIncrement = ; MongoClient;
...with mongoose
The plugin can be applied to particular schema and globally.
mongoosePlugin(schema, options)
- schema - mongoose.Schema
- options - Object:
- field - auto increment field name, default _id
- step - auto increment step, default 1
With single schema plugin
var mongoose = ;var autoIncrement = ; var schema = ...; schema;
Global plugin usage
While using plugin as global mongoose plugin it will be applied to all schemas with no {_id: false} option set.
var autoIncrement = ;var mongoose = ;mongoose; var schema1 = // _id field will be auto incremented integer ...; var schema2 = // plugin will not be applied ... _id: false;
Setting default options
var autoIncrement = ;autoIncrement;
Notes
You cannot set initial values for auto increment fields by the module. If you need it you can always set them directly via mongodb. Find a record with _id 'collectionName' in the collection 'counters' and set field 'seq' to required value.
Counters collection structure:
_id: collectionName // name of the collection for which auto increment id field is set field: fieldName // name of the field to auto increment in the collection collectionName seq: integerValue // last auto increment value used