@hsa-technologies-00/mongoose-automatic-reference
v1.0.0
Published
Mongoose plugin for automatic reference IDs like CERT-1, CERT-2 etc.
Maintainers
Readme
Mongoose Automatic Reference Plugin
Table of Contents
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-referenceor
yarn add @hsa-technologies-00/mongoose-automatic-referenceUsage
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
| Option | Type | Required | Default | Description |
| -------------- | ------ | -------- | ------- | ---------------------------------------- |
| fieldName | string | Yes | - | The field name to store the generated ID |
| prefix | string | Yes | - | The prefix for the reference ID |
| initialValue | number | No | 1 | Starting 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 testTest 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! 🚀
