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

mongoosejs-soft-delete

v1.0.2

Published

Plugin for mongoose soft delete

Downloads

988

Readme

Mongoosejs Soft Delete Plugin

Build Status GitHub license

A lightweight plugin that enables the soft delete functionality for documents in MongoDB. This code is based on mongoose-delete.

Usage Guidelines

How it Works

Functions Support

Handling Hooks

Installation

Install using npm

npm install mongoosejs-soft-delete

Usage

You can use this plugin with or without passing the options to the plugin.

Basic Usage

let softDelete = require('mongoosejs-soft-delete');
let SampleSchema = new mongoose.Schema({
    comment: String
})
SampleSchema.plugin(softDelete) //Without passing any parameters.

let Sample = mongoose.model('Sample', SampleSchema);
let document = new Sample({
    comment: "This plugin is awesome."
});
   
let sampleId = mongoose.Types.ObjectId("507f1f77bcf86cd799439011");

//This will do soft delete for one document.
Sample.removeOne({ _id: sampleId }, function (err, res) {});
Sample.findByIdDeleted(sampleId, function(err, doc) {
    //doc.deletedAt will be current timestamp
    //doc.deleted will be true
})

//This will do soft delete for multiple document.
Sample.removeMany({ _id: sampleId }, function (err, res) {});

// If you want to perform hard delete.
//For deleting one document.
Sample.deleteOne({ _id: sampleId }, callback);

//For deleting multiple documents.
Sample.deleteMany(conditions, callback);

By default, basic usage will set the deleted and deletedAt field. The type of deleted field will be Boolean whereas deletedAt will have the current timestamp.

Advance Usage

If you want to change the default behaviour of the plugin. For example, instead of deletedAt you want to have custom field and the value of that custom field should be a custom function then you can use this second option.

let softDelete = require('mongoosejs-soft-delete');
let SampleSchema = new mongoose.Schema({
    comment: String
})

//To define our on custom field pass two params: index and define that index.

function getCustom() {
    return true;
}

SampleSchema.plugin(softDelete, { index: 'custom', custom: getCustom()) 

let Sample = mongoose.model('Sample', SampleSchema);
let document = new Sample({
    comment: "This plugin is awesome."
});
   
let sampleId = mongoose.Types.ObjectId("507f1f77bcf86cd799439011");

//This will do soft delete for one document.
Sample.removeOne({ _id: sampleId }, function (err, res) {});
Sample.findByIdDeleted(sampleId, function(err, doc) {
    //doc.custom will be true
    //doc.deleted will be true
})

//This will do soft delete for multiple document.
Sample.removeMany({ _id: sampleId }, function (err, res) {});

// If you want to perform hard delete.
//For deleting one document.
Sample.deleteOne({ _id: sampleId }, callback);

//For deleting multiple documents.
Sample.deleteMany(conditions, callback);

If you are passing your own custom function make sure it has some return type. Any return type except the function.

Also you can directly assign certain value the index field value.

    SampleSchema.plugin(softDelete, { index: 'custom', custom: true });

How it works

We haven't override the mongoose deleteOne and deleteMany function so it will perform hard delete (not soft delete).

Below table shows the functions that will do soft delete.

| Mongoose Function | Under Hood Performs | |:-----------------:|:--------------------:| | findById | findOne | | findOneAndRemove | findOneAndUpdate | | findOneAndDelete | findOneAndUpdate | | findByIdAndRemove | findByIdAndUpdate | | findByIdAndDelete| findByIdAndUpdate | | removeOne | updateOne | | removeMany | updateMany |

Functions Support

For the following method we have methods to query the non-soft-deleted documents, soft deleted (suffix: Deleted) document and both of the documents(suffix: withDeleted).

| Non-Deleted Documents | Soft Deleted Documents | All Documents | |:---------------------:|:---------------------------:|:-----------------------------:| |find | findDeleted | findWithDeleted | |findByIdAndUpdate | findByIdAndUpdateDeleted | findByIdAndWithUpdateDeleted | |findOne | findOneDeleted | findOneWithDeleted | |findOneAndUpdate | findOneAndUpdateDeleted | findOneAndUpdateWithDeleted | |replaceOne | replaceOneDeleted | replaceOneWithDeleted | |updateMany | updateManyDeleted | updateManyWithDeleted | |updateOne | updateOneDeleted | updateOneWithDeleted |

Hard and soft delete functions

The following method performs delete feature.

| Function | Type |
|:---------------------:|:----------:| | deleteOne | Hard Delete| | deleteMany | Hard Delete| | removeOne | Soft Delete| | removeMany | Soft Delete|

Hooks

Using mongoose hooks for soft delete. There is always a case like you want to remove the related documents on soft delete then you can always use the below hook.

Note: This hook is only useful if you call removeOne and removeMany and always passing the required constraint for fetching relational data

   let softDelete = require('mongoosejs-soft-delete');
   let SampleSchema = new mongoose.Schema({
       comment: String
   })
   
   SampleSchema.plugin(softDelete);
   
   //This hook will run if you use Model.removeOne() method.
   SampleSchema.post('updateOne', async function() {
        if (this._update.deleted) {
            //this doc is deleted so you can easily perform clean up here.
        }
   });
   
   
   //This hook will run if you use Model.removeMany() method.
   SampleSchema.post('updateMany', async function() {
        if (this._update.deleted) {
            //do your clean up work.
        }
   });
 

Also, you can use the _conditions to the query parameters that you passed while calling the removeMany or removeOne method.

License

Copyright (c) 2018 Hardik Patel and Parth Patel Code released under MIT