npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

mongo-base-crud

v0.4.1

Published

Class to handler access and handler database

Readme

🧩 mongo-base-crud

TypeScript library to simplify CRUD operations with MongoDB.
Ideal for whitelabel projects, with support for multiple databases, dynamic aliases, and Singleton pattern.


📦 Installation

npm install mongo-base-crud

⚙️ Configuration

Create a .env file with the following variables:

MONGO_URL="mongodb://admin:admin@localhost:27017"
MONGO_DB=test
MONGO_PREFIX_NAME=test_
MONGO_DISABLE_PLURAL=true
  • MONGO_URL: MongoDB connection URL
  • MONGO_DB: Base database name
  • MONGO_PREFIX_NAME: Prefix used for multi-tenant or whitelabel projects
  • MONGO_DISABLE_PLURAL: (optional) if set to true, prevents automatic pluralization of collection names

📌 Manual configuration example: you can override this programmatically by passing disablePlural: true in the connection config:

await BaseCrud.getInstance("exact_collection_name", "my_db", {}, 1, {
  fullUrl: "mongodb://localhost:27017",
  disablePlural: true,
});

🧠 About getInstance and .instance()

🔹 BaseCrud.getInstance(...)
Creates or returns a global Singleton instance. Useful for dynamic or generic cases. The instance key is based on dbName_collectionName.

🔸 .instance(alias: string)
Recommended method to create reusable repositories with unique names, ideal for whitelabel projects. Internally uses getInstance with a custom key based on the alias.


🧪 Example with .instance()

import { Singleton } from "typescript-singleton";
import { BaseCrud } from "mongo-base-crud";

interface User {
  id: string;
  name: string;
}

export class UserRepository extends BaseCrud<User> {
  public static instance(clinicAlias: string): UserRepository {
    const dbName = `clinic_${clinicAlias}`;
    return Singleton.getInstance<UserRepository>(
      `UserRepo_${clinicAlias}`, // unique instance key
      UserRepository,
      "users",
      dbName,
      { name: 1 } // indexes
    );
  }

  constructor(collection = "users", dbName = "default", indexes = {}) {
    super(collection, dbName, indexes);
  }
}

📚 Available Methods

🧩 save(data: object): Promise<DocumentWithId>

Creates or completely replaces a document. If id is present, acts as an upsert.

✅ Example 1

const saveResult = await UserRepository.instance("acme").save({
  name: "John"
});

✅ Example 2

await UserRepository.instance("acme").save({
  id: "my-custom-id",
  name: "Mary"
});

✏️ update(data: { id: string, ... }): Promise<DocumentWithId>

Fully updates a document based on the provided id.


🧩 partialUpdate(id: string, data: object): Promise<DocumentWithId>

Partially updates only the provided fields of a document.


🔍 find(filter?, select?, skip?, limit?, orderBy?, direction?, searchValue?, searchFields?): Promise<List<T>>

Performs a filtered, paginated search with optional sorting and text search on multiple fields.


📋 findAll(filter?, select?, orderBy?, direction?, searchValue?, searchFields?): Promise<T[]>

Same as find, but returns all results without pagination.


🔍 getById(id: string): Promise<T | null>

Retrieves a document by its ID.


delete(id: string): Promise<boolean>

Deletes a document by its ID.


🔄 aggregate(pipeline: object[]): Promise<T[]>

Executes an aggregation pipeline.
Example:

const result = await UserRepository.instance("acme").aggregate([
  { $group: { _id: "$details.name", count: { $sum: 1 } } },
  { $project: { _id: 0, name: "$_id", count: 1 } }
]);

🏗️ Generic Usage with getInstance(...)

const crud = BaseCrud.getInstance<{ id: string; name: string }>(
  "users",
  "clinic_acme",
  { name: 1 }
);

await crud.save({ name: "Example" });

📌 Requirements

  • Node.js >= 14
  • MongoDB >= 4.x
  • TypeScript

✅ Tests

Example using Vitest:

it("should save a new document", async () => {
  const result = await UserRepository.instance("acme").save({ name: "Test" });
  expect(result.id).toBeDefined();
});

🤝 Contributing

Pull requests are welcome! Suggestions, usage examples, and improvements are greatly appreciated.


📝 License

Apache-2.0 © IDress : Renato Miawaki