mongo-autoincrement
TypeScript icon, indicating that this package has built-in type declarations

1.0.1 • Public • Published

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(dbDb, collectionstring, fieldstring, 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',
  current1 // 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

Package Sidebar

Install

npm i mongo-autoincrement

Weekly Downloads

25

Version

1.0.1

License

MIT

Unpacked Size

6.16 kB

Total Files

5

Last publish

Collaborators

  • fox1t