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 🙏

© 2024 – Pkg Stats / Ryan Hefner

mongoose-soft-delete-plugin

v1.1.1

Published

A Mongoose plugin that adds soft delete functionality and active/inactive status to your Mongoose models.

Downloads

10

Readme

mongoose-soft-delete-plugin

A Mongoose plugin that adds soft delete functionality and active/inactive status to your Mongoose models, enabling efficient data management without permanently removing documents from the database.

Features

  • Soft Delete: Mark documents as deleted without removing them from the database.
  • Active/Inactive Status: Easily manage the state of documents with active and inactive flags.
  • Flexible Querying: Find non-deleted and active documents effortlessly.
  • Middleware Support: Automatically filter out deleted and inactive documents in query operations.
  • Restore Functionality: (Optional) Restore soft-deleted documents while managing their active state.

Installation

To install the plugin, run:

npm install mongoose-soft-delete-plugin

Usase

After installing the package, you can easily integrate it into your Mongoose schema by following these steps:

Step 1: Add the plugin to your schema.

First, define a Mongoose schema and apply the mongoose-soft-delete-plugin plugin to it:

const mongoose = require('mongoose');
const softDeletePlugin = require('mongoose-soft-delete-plugin');

// Define your schema
const userSchema = new mongoose.Schema({
  name: { type: String, required: true },
  email: { type: String, required: true, unique: true }
});

// Apply the soft delete plugin
userSchema.plugin(softDeletePlugin);

// Create the model
const User = mongoose.model('User', userSchema);

Step 2: Soft Delete a Document. Once you’ve applied the plugin, you can soft delete a document by calling the softDelete method on a Mongoose model instance:

async function softDeleteUser(userId) {
  const user = await User.findById(userId);
  if (user) {
    await user.softDelete();
    console.log('User soft deleted:', user);
  }
}

Step 3: Deactivate a Document. To deactivate a document (mark it as inactive), use the deactivate method:

async function deactivateUser(userId) {
  const user = await User.findById(userId);
  if (user) {
    await user.deactivate();
    console.log('User deactivated:', user);
  }
}

Step 4: Activate a Document.

You can reactivate a previously deactivated document using the activate method:

async function activateUser(userId) {
  const user = await User.findById(userId);
  if (user) {
    await user.activate();
    console.log('User activated:', user);
  }
}

Step 5: Query Active, Non-Deleted Documents.

The plugin provides a method findActiveNonDeleted to query only the documents that are both active and not soft deleted:

async function getActiveUsers() {
  const activeUsers = await User.findActiveNonDeleted();
  console.log('Active and non-deleted users:', activeUsers);
}

Step 6: Use Middleware for Filtering.

By default, the plugin adds middleware that filters out soft-deleted and inactive documents when you use find or findOne queries:

async function findUsers() {
  const users = await User.find();
  console.log('Filtered users (non-deleted and active only):', users);
}

Step 7: Restore Soft-Deleted Documents (Optional).

If you want to restore a soft-deleted document, simply update its isDeleted field back to false:

async function restoreUser(userId) {
  const user = await User.findById(userId);
  if (user && user.isDeleted) {
    user.isDeleted = false;
    user.deletedAt = null;
    await user.save();
    console.log('User restored:', user);
  }
}

Example

Here’s a complete example showing how to use the plugin with a User model:

const mongoose = require('mongoose');
const softDeletePlugin = require('mongoose-soft-delete-plugin');

// Define schema
const userSchema = new mongoose.Schema({
  name: { type: String, required: true },
  email: { type: String, required: true, unique: true }
});

// Apply the soft delete plugin
userSchema.plugin(softDeletePlugin);

// Create the model
const User = mongoose.model('User', userSchema);

async function run() {
  await mongoose.connect('mongodb://localhost:27017/testDB');

  // Create a user
  const user = new User({ name: 'John Doe', email: '[email protected]' });
  await user.save();
  console.log('User created:', user);

  // Soft delete the user
  await user.softDelete();
  console.log('User soft deleted:', user);

  // Find all active, non-deleted users
  const activeUsers = await User.findActiveNonDeleted();
  console.log('Active users:', activeUsers);
  
  await mongoose.connection.close();
}

run().catch(console.error);

Key Sections in the Usage:

  1. Step 1: Add the Plugin to Your Schema: Explains how to add the plugin to a Mongoose schema.
  2. Step 2: Soft Delete a Document: Shows how to use the soft delete method.
  3. Step 3: Deactivate a Document: Demonstrates how to deactivate a document.
  4. Step 4: Activate a Document: Reactivate a previously deactivated document.
  5. Step 5: Query Active, Non-Deleted Documents: Use the findActiveNonDeleted method for querying active, non-deleted data.
  6. Step 6: Use Middleware for Filtering: Automatically exclude soft-deleted or inactive documents from standard find queries.
  7. Step 7: Restore Soft-Deleted Documents (Optional): Explains how to manually restore a soft-deleted document.

This structure ensures that users of your plugin have a clear, step-by-step guide on how to integrate and use the plugin in their own projects!