als-mongo-remove

1.0.0 • Public • Published

als-mongo-remove

A lightweight library for managing removal of Mongoose documents with support for soft delete, hooks, and dependent model cleanup.

Overview

als-mongo-remove is a utility for removing Mongoose documents, with features like:

  • Soft delete support.
  • Hooks for extending functionality before and after operations.
  • Automatic cleanup of related documents via dependency population.

Installation

npm install als-mongo-remove

Quick Start

const mongoose = require('mongoose');
const MongoRemove = require('als-mongo-remove');

const Post = mongoose.model('Post', new mongoose.Schema({
  title: String,
  content: String,
  isDeleted: { type: Boolean, default: false },
}));

const Comment = mongoose.model('Comment', new mongoose.Schema({
  postId: { type: mongoose.Schema.Types.ObjectId, ref: 'Post' },
  content: String,
  isDeleted: { type: Boolean, default: false },
}));

const remover = new MongoRemove(Post, { softDelete: true });
remover.populate('Comment');

// Remove a post by ID
remover.removeById('64f7c1ad2f12e828b0eabc12').then((result) => {
  console.log(result); // { deleted: true }
});

Class API: MongoRemove

Constructor

constructor(Model: mongoose.Model<any>, options?: {
  softDelete?: boolean;
  hooks?: {
    beforeRemoveOne?: (filter: object, context: MongoRemove) => Promise<void>;
    afterRemoveOne?: (doc: object, context: MongoRemove) => Promise<void>;
    beforeRemoveMany?: (filter: object, context: MongoRemove) => Promise<void>;
    afterRemoveMany?: (result: object, context: MongoRemove) => Promise<void>;
  };
  referenceKey?: string;
  logger?: { error: (message: string) => void; warn?: (message: string) => void };
});
  • Parameters:
    • Model (required): The Mongoose model to manage.
    • options: Configuration options.
      • softDelete (default: false): Enables soft deletion by setting isDeleted: true instead of removing the document.
      • hooks: Lifecycle hooks.
      • referenceKey (default: <modelName>Id): Field used for dependencies.
      • logger (default: console): Logger instance for error/warning messages.

Methods

populate

populate(...models: string[]): this;

Adds related models for dependent document cleanup.

  • Parameters:
    • models: Names of related models defined in mongoose.models.
  • Returns: this
  • Errors:
    • Logs an error if a specified model does not exist in mongoose.models.

removeOne

removeOne(filter: object): Promise<{ deleted: boolean; error?: Error }>;

Removes a single document based on the provided filter.

  • Parameters:
    • filter: MongoDB query filter to identify the document.
  • Returns:
    • { deleted: true } if successful.
    • { deleted: false, error } if the operation fails.
  • Errors:
    • Adds error to this.errors array and logs it.

removeMany

removeMany(filter: object): Promise<{ deletedCount: number }>;

Removes multiple documents based on the provided filter.

  • Parameters:
    • filter: MongoDB query filter to identify documents.
  • Returns:
    • { deletedCount } indicating the number of documents removed.
  • Errors:
    • Adds error to this.errors array and logs it.

removeById

removeById(id: string): Promise<{ deleted: boolean }>;

Removes a single document by its ID.

  • Parameters:
    • id: The document's _id.
  • Returns:
    • { deleted: true } if successful.
    • { deleted: false } if the operation fails or ID is invalid.
  • Errors:
    • Adds error to this.errors array if the ID is invalid or document not found.

removeByIds

removeByIds(ids: string[]): Promise<{ deletedCount: number }>;

Removes multiple documents by their IDs.

  • Parameters:
    • ids: Array of document IDs.
  • Returns:
    • { deletedCount } indicating the number of documents removed.
  • Errors:
    • Skips invalid IDs and logs a warning for each.

removePopulation

removePopulation(ids: string[]): Promise<object[]>;

Removes related documents from populated models.

  • Parameters:
    • ids: Array of parent document IDs.
  • Returns:
    • Array of results for each dependent model.
  • Errors:
    • Logs an error for any missing or invalid related models.

validateId

validateId(id: string): string | false;

Validates a MongoDB ObjectId.

  • Parameters:
    • id: The ID to validate.
  • Returns:
    • The valid ID as a string, or false if invalid.
  • Errors:
    • Logs an error for invalid IDs.

Error Handling

  • Errors are collected in this.errors and logged via the provided logger or console.
  • Common errors include:
    • Invalid MongoDB IDs.
    • Non-existent models in populate.
    • Document not found for the given filter.

Example of handling errors:

const remover = new MongoRemove(Post);
await remover.removeById('invalidId123');

if (remover.errors.length > 0) {
  console.error('Errors occurred:', remover.errors);
}

TypeScript Interface Summary

class MongoRemove {
  constructor(Model: mongoose.Model<any>, options?: {
    softDelete?: boolean;
    hooks?: {
      beforeRemoveOne?: (filter: object, context: MongoRemove) => Promise<void>;
      afterRemoveOne?: (doc: object, context: MongoRemove) => Promise<void>;
      beforeRemoveMany?: (filter: object, context: MongoRemove) => Promise<void>;
      afterRemoveMany?: (result: object, context: MongoRemove) => Promise<void>;
    };
    referenceKey?: string;
    logger?: { error: (message: string) => void; warn?: (message: string) => void };
  });

  populate(...models: string[]): this;
  removeOne(filter: object): Promise<{ deleted: boolean; error?: Error }>;
  removeMany(filter: object): Promise<{ deletedCount: number }>;
  removeById(id: string): Promise<{ deleted: boolean }>;
  removeByIds(ids: string[]): Promise<{ deletedCount: number }>;
  removePopulation(ids: string[]): Promise<object[]>;
  validateId(id: string): string | false;
}

/als-mongo-remove/

    Package Sidebar

    Install

    npm i als-mongo-remove

    Weekly Downloads

    0

    Version

    1.0.0

    License

    MIT

    Unpacked Size

    27.5 kB

    Total Files

    10

    Last publish

    Collaborators

    • alexsorkin