Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

mongoose-delete

dsanel169.8kMIT1.0.2TypeScript support: definitely-typed

Mongoose soft delete plugin

mongoose, soft, delete, delete, remove, plugin

readme

Mongoose Delete Plugin

mongoose-delete is simple and lightweight plugin that enables soft deletion of documents in MongoDB. This code is based on riyadhalnur's plugin mongoose-softdelete.

Build Status

Features

Installation

Install using npm

npm install mongoose-delete

TypeScript support

The plugin currently does not have its own type definition. Please be free to use @types/mongoose-delete.

In doing so, you should make use of the SoftDeleteModel type, instead of the Model type.

import { Schema, model, connect } from 'mongoose';
import { SoftDeleteModel }, MongooseDelete from 'mongoose-delete';

interface Pet extends SoftDeleteDocument {
  name: string;
}

const PetSchema = new Schema<Pet>({
    name: String
});

PetSchema.plugin(MongooseDelete, { deletedBy: true, deletedByType: String });

const model: SoftDeleteModel = model<Pet>('Pet', PetSchema);

export default model;

Usage

We can use this plugin with or without options.

Simple usage

var mongoose_delete = require('mongoose-delete');

var PetSchema = new Schema({
    name: String
});

PetSchema.plugin(mongoose_delete);

var Pet = mongoose.model('Pet', PetSchema);

var fluffy = new Pet({ name: 'Fluffy' });

fluffy.save(function () {
    // mongodb: { deleted: false, name: 'Fluffy' }

    // note: you should invoke exactly delete() method instead of standard fluffy.remove()
    fluffy.delete(function () {
        // mongodb: { deleted: true, name: 'Fluffy' }

        fluffy.restore(function () {
            // mongodb: { deleted: false, name: 'Fluffy' }
        });
    });

});

var examplePetId = mongoose.Types.ObjectId("53da93b16b4a6670076b16bf");

// INFO: Example usage of deleteById static method
Pet.deleteById(examplePetId, function (err, petDocument) {
    // mongodb: { deleted: true, name: 'Fluffy', _id: '53da93b1...' }
});

Save time of deletion

var mongoose_delete = require('mongoose-delete');

var PetSchema = new Schema({
    name: String
});

PetSchema.plugin(mongoose_delete, { deletedAt : true });

var Pet = mongoose.model('Pet', PetSchema);

var fluffy = new Pet({ name: 'Fluffy' });

fluffy.save(function () {
    // mongodb: { deleted: false, name: 'Fluffy' }

    // note: you should invoke exactly delete() method instead of standard fluffy.remove()
    fluffy.delete(function () {
        // mongodb: { deleted: true, name: 'Fluffy', deletedAt: ISODate("2014-08-01T10:34:53.171Z")}

        fluffy.restore(function () {
            // mongodb: { deleted: false, name: 'Fluffy' }
        });
    });

});

Who has deleted the data?

var mongoose_delete = require('mongoose-delete');

var PetSchema = new Schema({
    name: String
});

PetSchema.plugin(mongoose_delete, { deletedBy : true });

var Pet = mongoose.model('Pet', PetSchema);

var fluffy = new Pet({ name: 'Fluffy' });

fluffy.save(function () {
    // mongodb: { deleted: false, name: 'Fluffy' }

    var idUser = mongoose.Types.ObjectId("53da93b16b4a6670076b16bf");

    // note: you should invoke exactly delete() method instead of standard fluffy.remove()
    fluffy.delete(idUser, function () {
        // mongodb: { deleted: true, name: 'Fluffy', deletedBy: ObjectId("53da93b16b4a6670076b16bf")}

        fluffy.restore(function () {
            // mongodb: { deleted: false, name: 'Fluffy' }
        });
    });

});

The type for deletedBy does not have to be ObjectId, you can set a custom type, such as String.

var mongoose_delete = require('mongoose-delete');

var PetSchema = new Schema({
    name: String
});

PetSchema.plugin(mongoose_delete, { deletedBy: true, deletedByType: String });

var Pet = mongoose.model('Pet', PetSchema);

var fluffy = new Pet({ name: 'Fluffy' });

fluffy.save(function () {
    // mongodb: { deleted: false, name: 'Fluffy' }

    var idUser = "my-custom-user-id";

    // note: you should invoke exactly delete() method instead of standard fluffy.remove()
    fluffy.delete(idUser, function () {
        // mongodb: { deleted: true, name: 'Fluffy', deletedBy: 'my-custom-user-id' }

        fluffy.restore(function () {
            // mongodb: { deleted: false, name: 'Fluffy' }
        });
    });
});

Bulk delete and restore

var mongoose_delete = require('mongoose-delete');

var PetSchema = new Schema({
    name: String,
    age: Number
});

PetSchema.plugin(mongoose_delete);

var Pet = mongoose.model('Pet', PetSchema);

var idUser = mongoose.Types.ObjectId("53da93b16b4a6670076b16bf");

// Delete multiple object, callback
Pet.delete(function (err, result) { ... });
Pet.delete({age:10}, function (err, result) { ... });
Pet.delete({}, idUser, function (err, result) { ... });
Pet.delete({age:10}, idUser, function (err, result) { ... });

// Delete multiple object, promise
Pet.delete().exec(function (err, result) { ... });
Pet.delete({age:10}).exec(function (err, result) { ... });
Pet.delete({}, idUser).exec(function (err, result) { ... });
Pet.delete({age:10}, idUser).exec(function (err, result) { ... });

// Restore multiple object, callback
Pet.restore(function (err, result) { ... });
Pet.restore({age:10}, function (err, result) { ... });

// Restore multiple object, promise
Pet.restore().exec(function (err, result) { ... });
Pet.restore({age:10}).exec(function (err, result) { ... });

Method overridden

We have the option to override all standard methods or only specific methods. Overridden methods will exclude deleted documents from results, documents that have deleted = true. Every overridden method will have two additional methods, so we will be able to work with deleted documents.

only not deleted documents only deleted documents all documents
count() countDeleted countWithDeleted
countDocuments() countDocumentsDeleted countDocumentsWithDeleted
find() findDeleted findWithDeleted
findOne() findOneDeleted findOneWithDeleted
findOneAndUpdate() findOneAndUpdateDeleted findOneAndUpdateWithDeleted
update() updateDeleted updateWithDeleted
updateOne() updateOneDeleted updateOneWithDeleted
updateMany() updateManyDeleted updateManyWithDeleted
aggregate() aggregateDeleted aggregateWithDeleted
findById() Please use findOne Please use findOneWithDeleted
findByIdAndUpdate() Please use findOneAndUpdateDeleted Please use findOneAndUpdateWithDeleted

Examples how to override one or multiple methods

var mongoose_delete = require('mongoose-delete');

var PetSchema = new Schema({
    name: String
});

// Override all methods
PetSchema.plugin(mongoose_delete, { overrideMethods: 'all' });
// or
PetSchema.plugin(mongoose_delete, { overrideMethods: true });

// Overide only specific methods
PetSchema.plugin(mongoose_delete, { overrideMethods: ['count', 'find', 'findOne', 'findOneAndUpdate', 'update'] });
// or
PetSchema.plugin(mongoose_delete, { overrideMethods: ['count', 'countDocuments', 'find'] });
// or (unrecognized method names will be ignored)
PetSchema.plugin(mongoose_delete, { overrideMethods: ['count', 'find', 'errorXyz'] });


var Pet = mongoose.model('Pet', PetSchema);

// Example of usage overridden methods

Pet.find(function (err, documents) {
  // will return only NOT DELETED documents
});

Pet.findDeleted(function (err, documents) {
  // will return only DELETED documents
});

Pet.findWithDeleted(function (err, documents) {
  // will return ALL documents
});

Disable model validation on delete

var mongoose_delete = require('mongoose-delete');

var PetSchema = new Schema({
    name: { type: String, required: true }
});

// By default, validateBeforeDelete is set to true
PetSchema.plugin(mongoose_delete);
// the previous line is identical to next line
PetSchema.plugin(mongoose_delete, { validateBeforeDelete: true });

// To disable model validation on delete, set validateBeforeDelete option to false
PetSchema.plugin(mongoose_delete, { validateBeforeDelete: false });

// NOTE: This is based on existing Mongoose validateBeforeSave option
// http://mongoosejs.com/docs/guide.html#validateBeforeSave

Disable model validation on restore

var mongoose_delete = require('mongoose-delete');

var PetSchema = new Schema({
    name: { type: String, required: true }
});

// By default, validateBeforeRestore is set to true
PetSchema.plugin(mongoose_delete);
// the previous line is identical to next line
PetSchema.plugin(mongoose_delete, { validateBeforeRestore: true });

// To disable model validation on restore, set validateBeforeRestore option to false
PetSchema.plugin(mongoose_delete, { validateBeforeRestore: false });

// NOTE: This is based on existing Mongoose validateBeforeSave option
// http://mongoosejs.com/docs/guide.html#validateBeforeSave

Create index on fields

var mongoose_delete = require('mongoose-delete');

var PetSchema = new Schema({
    name: String
});

// Index all field related to plugin (deleted, deletedAt, deletedBy)
PetSchema.plugin(mongoose_delete, { indexFields: 'all' });
// or
PetSchema.plugin(mongoose_delete, { indexFields: true });

// Index only specific fields
PetSchema.plugin(mongoose_delete, { indexFields: ['deleted', 'deletedBy'] });
// or
PetSchema.plugin(mongoose_delete, { indexFields: ['deletedAt'] });

License

The MIT License

Copyright (c) 2014 Sanel Deljkic http://dsanel.github.io/

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

changelog

[v1.0.2]

February 5, 2024

  • Update devDependencies to "mongoose": "^8.1.1"
  • peerDependencies for mongoose set to "5.x || 6.x || 7.x || 8.x" (RajatJain4061) #148
  • fix test: count() -> should return 3 documents

[v1.0.1]

June 13, 2023

  • fix: aggregateWithDeleted returns no result with Discriminators #130
  • Update devDependencies to "mongoose": "^7.2.4"

[v1.0.0]

June 12, 2023

  • BREAKING CHANGE: remove support for Mongoose 4.x
  • Upgrade all test to support mongoose 5, 6, 7
  • Refactor all tests to use async/await, remove callbacks Emanuel Canavesio
  • Update version of mongoose, mocha, chai in devDependencies Emanuel Canavesio
  • peerDependencies for mongoose set to "5.x || 6.x || 7.x"
  • Setup GitHub action for tests
    • OS: ubuntu-20.04, ubuntu-22.04
    • Node: 14, 16, 18
    • MongoDB: 4.4.18, 5.0.14, 6.0.4
  • Add validateBeforeRestore option AnthonyNabil
  • Fixed Static Restore does not remove deletedAt and deletedBy benny1hk

[v0.5.4]

August 31, 2021

  • Upgrade all test to support mongoose 5.x and 6.x
  • Stop using TravicCI as test runner
  • Setup GitHub action for tests
    • Node: 12, 14, 16
    • MongoDB: 4.0, 4.2, 4.4
  • Upgrade Mongoose ^6 in devDependencies
  • Add Mongoose 6 into peerDependencies #105 (@Paso)

[v0.5.3]

November 19, 2020

  • Add option to populate deleted documents #40 (@sven)
  • Update documentation for aggregate (@Jericho1060)
  • Update mocha -> 8.x
  • fix: deprecation warning for collection.update when user overrides update method #81 #78 (@nsine)
  • fix: nyc moved into devDependencies #80 (@isikhi)

[v0.5.2]

April 1, 2020

  • Add option to override aggregate (@shimonbrandsdorfer)
  • Upgrade all devDependencies to latest versions
  • Remove Istanbul coverage tool

[v0.5.1]

September 3, 2019

  • Add option to disable use of $ne operator using {use$neOperator: false} (@bdelville, @gabzim) #50
  • Fix Mongoose DeprecationWarning: collection.update is deprecated (@cardimajs, @jebarjonet)
  • Upgrade all devDependencies to latest versions
  • Fix security vulnerabilities in dependencies
  • Add additional tests for updateMany, countDocuments, use$neOperator
  • Setup .travis.yml to test plugin on Node: 12, 11, 10, 9, 8, 7, 6, 5, 4

[v0.5.0]

December 10, 2018

  • Add support to mongoose 5.x (@joelmukuthu, @gforge)
  • Add deleteById static method #16
  • Add countDocuments method with related override methods (only for v5 Mongoose) #45
  • Upgrade all devDependencies to latest versions
  • Setup .travis.yml to test plugin on Node: 10, 9, 8, 7, 6, 5, 4
  • Setup .travis.yml to use `coveralls@3.0.2`
  • Add additional tests

[v0.4.0]

July 10, 2016

  • Add custom typeKey support #22
  • Add option to set custom type for deletedBy
  • Support instance method delete promise
  • Add specification about remove() to README

[v0.3.4]

June 20, 2016

  • Methods override fix for existent DB #11
  • Option to create indexes for deleted, deletedAt, deletedBy, related to #12

[v0.3.3]

July 1, 2016

  • Default delete set to false #10

[v0.3.2]

April 26, 2016

  • Correct field name into documentation, validateBeforeDelete

[v0.3.1]

April 20, 2016

  • Add option to disable validation on delete #6

[v0.3.0]

Mar 11, 2016

  • Bulk delete and restore
  • Remove requirement for callback in delete() and restore()

[v0.2.1]

Feb 1, 2016

  • Add option to override static model methods (count, find, findOne, findOneAndUpdate, update)
  • Add additional methods for overridden static methods:
only not deleted documents only deleted documents all documents
count() countDeleted countWithDeleted
find() findDeleted findWithDeleted
findOne() findOneDeleted findOneWithDeleted
findOneAndUpdate() findOneAndUpdateDeleted findOneAndUpdateWithDeleted
update() updateDeleted updateWithDeleted

[v0.1.1]

Aug 1, 2014

  • Initial version
  • Add deleted (true-false) key on document
  • Add deletedAt key to store time of deletion
  • Add deletedBy key to record who deleted document
  • Restore deleted documents, restore() method