Socket
Book a DemoInstallSign in
Socket

@hsa-technologies-00/mongoose-automatic-reference

Package Overview
Dependencies
Maintainers
1
Versions
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@hsa-technologies-00/mongoose-automatic-reference

Mongoose plugin for automatic reference IDs like CERT-1, CERT-2 etc.

latest
Source
npmnpm
Version
1.0.0
Version published
Maintainers
1
Created
Source

Mongoose Automatic Reference Plugin

Table of Contents

  • Overview
  • Installation
  • Usage
  • API Documentation
  • Examples
  • Advanced Configuration
  • Testing
  • Contributing
  • License

Overview

The @hsa-technologies-00/mongoose-automatic-reference plugin automatically generates incrementing reference IDs for your Mongoose documents (e.g., "DOC-1", "DOC-2"). It maintains counters in a separate MongoDB collection and provides thread-safe ID generation.

Key Features:

  • Automatic reference field generation
  • Configurable prefix (e.g., "DOC", "INV", "CERT")
  • Customizable starting sequence number
  • Thread-safe counter operations
  • TypeScript support

Installation

npm install @hsa-technologies-00/mongoose-automatic-reference

or

yarn add @hsa-technologies-00/mongoose-automatic-reference

Usage

Basic Usage

import mongoose from "mongoose";
import automaticReference from "@hsa-technologies-00/mongoose-automatic-reference";

const schema = new mongoose.Schema({ name: String });
schema.plugin(automaticReference, {
  fieldName: "docId", // Field to store the generated ID
  prefix: "DOC", // Prefix for the ID (e.g., DOC-1)
});

const Model = mongoose.model("Document", schema);

// When creating documents
const doc = await Model.create({ name: "Test" });
console.log(doc.docId); // Outputs "DOC-1"

With Custom Initial Value

schema.plugin(automaticReference, {
  fieldName: "certificateId",
  prefix: "CERT",
  initialValue: 1000, // Start counting from 1000 (CERT-1000)
});

API Documentation

Plugin Options

OptionTypeRequiredDefaultDescription
fieldNamestringYes-The field name to store the generated ID
prefixstringYes-The prefix for the reference ID
initialValuenumberNo1Starting number for the sequence

Examples

Multiple Models with Different Prefixes

// Certificates model
const certificateSchema = new mongoose.Schema({ name: String });
certificateSchema.plugin(automaticReference, {
  fieldName: "certId",
  prefix: "CERT",
});

// Invoices model
const invoiceSchema = new mongoose.Schema({ amount: Number });
invoiceSchema.plugin(automaticReference, {
  fieldName: "invoiceNumber",
  prefix: "INV",
  initialValue: 1000,
});

const Certificate = mongoose.model("Certificate", certificateSchema);
const Invoice = mongoose.model("Invoice", invoiceSchema);

// Usage
const cert = await Certificate.create({ name: "SSL Cert" });
const inv = await Invoice.create({ amount: 100 });

console.log(cert.certId); // e.g., "CERT-1"
console.log(inv.invoiceNumber); // e.g., "INV-1000"

Using in an Existing Collection

const existingSchema = new mongoose.Schema({
  /* ... */
});

// Add the plugin to existing collection
existingSchema.plugin(automaticReference, {
  fieldName: "legacyId",
  prefix: "LEG",
  initialValue: 5000, // Start after existing IDs
});

Advanced Configuration

Transaction Support

const session = await mongoose.startSession();
session.startTransaction();

try {
  const doc = await Model.create([{ name: "Tx Test" }], { session });
  await session.commitTransaction();
  console.log(doc[0].docId);
} catch (error) {
  await session.abortTransaction();
  throw error;
} finally {
  session.endSession();
}

Custom ID Formatting

Extend the plugin with custom formatting:

schema.plugin(automaticReference, {
  fieldName: "customId",
  prefix: "CUST",
  formatter: (prefix: string, num: number) => {
    const year = new Date().getFullYear();
    return `${year}-${prefix}-${String(num).padStart(5, "0")}`;
    // e.g., "2023-CUST-00001"
  },
});

Testing

To run tests:

npm test

Test environment requires:

  • MongoDB instance running (default: mongodb://localhost:27017/test_db)
  • Jest configured for TypeScript

Contributing

  • Fork the repository
  • Create a feature branch (git checkout -b feature/xyz)
  • Commit your changes (git commit -am 'Add feature xyz')
  • Push to the branch (git push origin feature/xyz)
  • Open a Pull Request

License

MIT © Md. Harun Or Rashid

Support

If you find this package useful, please consider giving it a ⭐️ on GitHub.

Enjoy building Mongoose plugins with ease! 🚀

Keywords

mongoose

FAQs

Package last updated on 05 Jul 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts