mongo-autoincrement

Autoincrement functionality for MongoDb.

Usage no npm install needed!

<script type="module">
  import mongoAutoincrement from 'https://cdn.skypack.dev/mongo-autoincrement';
</script>

README

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