Skip to content
Autoincrement functionality for MongoDb
TypeScript
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.vscode
src
test
.editorconfig
.gitignore
.prettierrc
LICENSE
README.md
azure-pipelines.yml
package.json
tsconfig.json
tslint.json

README.md

mongo-autoincrement mongo-autoincrement

built with typescript-lib-starter styled with prettier styled with prettier styled with prettier

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.

Install

$ npm install mongo-autoincrement

Usage

The module exports just one function:

autoIncrement(db: Db, collection: string, field: string, options?)

You can call it like this:

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')
})()

Using more than one field for a counter

For example

await autoIncrement(db, 'test', 'id', { filter: { tenantId: '1' } })

will add this counter:

{
  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.

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;

License

MIT

You can’t perform that action at this time.