Autoincrement functionality for MongoDb.
npm install mongo-autoincrement




This package brings auto increment functionality to MongoDb. It uses a collection (by default called counters) to store the current the sequential number. Every collection, field or even custom filter can be managed separately.
$ npm install mongo-autoincrementThe module exports just one function:
``typescript`
autoIncrement(db: Db, collection: string, field: string, options?)
You can call it like this:
`typescript
const { MongoClient } = require('mongodb')
const autoIncrement = require('mongo-autoincrement') // or import autoIncrement from 'mongo-autoincrement'
;(async () => {
// connect to mongodb server
const client = await MongoClient.connect(mongoUri, { useNewUrlParser: true })
// get mongo database instance
const db = client.db('test')
const one = await autoIncrement(db, 'test', 'id')
})()
`
`typescript`
await autoIncrement(db, 'test', 'id', { filter: { tenantId: '1' } })`
will add this counter:typescript`
{
collection: 'test',
field: 'id',
tenantId: '1',
current: 1 // this is the special autoincrement prop
}Options
For more specific query and configuration you can pass custom options.
`typescript``
interface Options {
filter?: object
collectionName?: string
step?: number
}
* filter: use this option if additional filters are needed.
* collectionName: sets autoIncrement collection name. Defaults to 'counters';
* step: lets you control the increse step. Defaults to 1;
MIT