Mongoose soft delete plugin
npm install @stenneepro/mongoose-soft-deleteMongoose Soft Delete Plugin
===========================
@stenneepro/mongoose-soft-delete is a simple and lightweight plugin that enables soft deletion of documents in MongoDB.
This code is based on plugin mongoose-delete.
But completely re-written in TypeScript with and using mongoose query helpers.
Note
The library is a successor of the existing plugin mongoose-delete-ts.
I had opened a PR to the existing plugin, but it seems the plugin is not maintained longer.

.withDeleted() to find all documents (even deleted ones).onlyDeleted() to only find deleted documents.notDeleted() to only find non-deleted documents (when method is excluded from overrideMethods)deleted=false
npm install @stenneepro/mongoose-soft-delete
`Usage
We can use this plugin with or without options.
$3
`typescript
import mongooseDelete, { DeletedDocument, DeletedModel, DeletedQuery } from '@stenneepro/mongoose-soft-delete';type PetDocument = Document & DeletedDocument & { name?: string };
type PetModel = Model & DeletedModel;
const PetSchema = new Schema({
name: String
});
PetSchema.plugin(mongooseDelete);
const Pet = mongoose.model('Pet', PetSchema);
const fluffy = new Pet({ name: 'Fluffy' });
await fluffy.save();
// mongodb: { deleted: false, name: 'Fluffy' }
await fluffy.deleteOne();
// mongodb: { deleted: true, name: 'Fluffy' }
await fluffy.restoreOne();
// mongodb: { deleted: false, name: 'Fluffy' }
`
$3
`typescript
import mongooseDelete, { DeletedDocument, DeletedAtDocument, DeletedModel, DeletedQuery } from '@stenneepro/mongoose-soft-delete';type PetDocument = Document & DeletedDocument & DeletedAtDocument & { name?: string };
type PetModel = Model & DeletedModel;
const PetSchema = new Schema({
name: String
});
PetSchema.plugin(mongooseDelete, { deletedAt: true });
const Pet = mongoose.model('Pet', PetSchema);
const fluffy = new Pet({ name: 'Fluffy' });
await fluffy.save();
// mongodb: { deleted: false, name: 'Fluffy' }
await fluffy.deleteOne();
// mongodb: { deleted: true, name: 'Fluffy', deletedAt: ISODate("2014-08-01T10:34:53.171Z")}
await fluffy.restoreOne();
// mongodb: { deleted: false, name: 'Fluffy' }
`
$3
`typescript
import mongooseDelete, { DeletedDocument, DeletedByDocument, DeletedModel, DeletedByModel, DeletedQuery } from '@stenneepro/mongoose-soft-delete';type PetDocument = Document & DeletedDocument & DeletedByDocument & { name?: string };
type PetModel = Model & DeletedModel & DeletedByModel;
const PetSchema = new Schema({
name: String
});
PetSchema.plugin(mongooseDelete, { deletedBy : true });
const Pet = mongoose.model('Pet', PetSchema);
const fluffy = new Pet({ name: 'Fluffy' });
await fluffy.save();
// mongodb: { deleted: false, name: 'Fluffy' }
const idUser = mongoose.Types.ObjectId("53da93b16b4a6670076b16bf");
// note: you should invoke deleteOneByUser()
await fluffy.deleteOneByUser(idUser);
// mongodb: { deleted: true, name: 'Fluffy', deletedBy: ObjectId("53da93b16b4a6670076b16bf")}
await fluffy.restoreOne();
// mongodb: { deleted: false, name: 'Fluffy' }
`The type for
deletedBy does not have to be ObjectId, you can set a custom type, such as String.`typescript
import mongooseDelete, { DeletedDocument, DeletedByDocument, DeletedModel, DeletedByModel, DeletedQuery } from '@stenneepro/mongoose-soft-delete';type PetDocument = Document & DeletedDocument & DeletedByDocument & { name?: string };
type PetModel = Model & DeletedModel & DeletedByModel;
const PetSchema = new Schema({
name: String
});
PetSchema.plugin(mongooseDelete, { deletedBy: { type: String } });
const Pet = mongoose.model('Pet', PetSchema);
const fluffy = new Pet({ name: 'Fluffy' });
await fluffy.save();
// mongodb: { deleted: false, name: 'Fluffy' }
const idUser = '123456789';
// note: you should invoke deleteOneByUser()
await fluffy.deleteOneByUser(idUser)
// mongodb: { deleted: true, name: 'Fluffy', deletedBy: '123456789' }
await fluffy.restoreOne()
`TypeScript support
$3
| Type | Adds property | Adds method
| --- | --- | ---
| DeletedDocument | document.deleted | document.deleteOne(), document.restoreOne()
| DeletedAtDocument | document.deletedAt |
| DeletedByDocument | document.deletedBy | document.deleteOneByUser(...)$3
| Type | Adds static methods
| --- | ---
| DeletedModel | Model.deleteOne(...), Model.deleteMany(...), Model.restoreOne(...), Model.restoreMany(...)
| DeletedByModel | Model.deleteOneByUser(...), Model.deleteManyByUser(...)$3
| Type | Adds query helpers
| --- | ---
| DeletedQuery | notDeleted(), onlyDeleted(), withDeleted()$3
`typescript
// Delete multiple object, callback
Pet.deleteMany({});
Pet.deleteMany({ age:10 });
Pet.deleteManyByUser(idUser, {});
Pet.deleteManyByUser(idUser, { age:10 });// Restore multiple object, callback
Pet.restoreMany({});
Pet.restoreMany({ age:10 });
`$3
By default, all standard methods will exclude deleted documents from results, documents that have
`deleted = true`. To change this behavior use query helper methods, so we will be able to work with deleted documents.| only not deleted documents | only deleted documents | all documents |
|----------------------------|-------------------------|-----------------------------|
| countDocuments() | countDocuments().onlyDeleted() | countDocuments().withDeleted() |
| find() | find().onlyDeleted() | find().withDeleted() |
| findById() | findById().onlyDeleted() | findById().withDeleted() |
| findOne() | findOne().onlyDeleted() | findOne().withDeleted() |
| findOneAndUpdate() | findOneAndUpdate().onlyDeleted() | findOneAndUpdate().withDeleted() |
| findByIdAndUpdate() | findByIdAndUpdate().onlyDeleted()| findByIdAndUpdate().withDeleted()|
| updateOne() | updateOne({ deleted: true }) | updateOne({ deleted: { $in: [true, false] }) |
| updateMany() | updateMany({ deleted: true }) | updateMany({ deleted: { $in: [true, false] }) |
| aggregate() | aggregate([], { onlyDeleted: true }) | aggregate([], { withDeleted: true }) |
$3
`typescript
// Override all methods (default)
PetSchema.plugin(mongooseDelete, { overrideMethods: true });// Overide only specific methods
PetSchema.plugin(mongooseDelete, { overrideMethods: ['count', 'find', 'findOne'] });
`$3
`typescript
// will return only NOT DELETED documents
const documents = await Pet.find();// will return only DELETED documents
const deletedDocuments = await Pet.find().onlyDeleted();
// will return ALL documents
const allDocuments = await Pet.find().withDeleted();
// will return only NOT DELETED documents (if method is not included in overrideMethods)
PetSchema.plugin(mongooseDelete, { overrideMethods: ['count'] });
const nonDeletedDocuments = await Pet.find().notDeleted();
`$3
`typescript
// By default, validateBeforeDelete is set to true
PetSchema.plugin(mongooseDelete);
// the previous line is identical to next line
PetSchema.plugin(mongooseDelete, { validateBeforeDelete: true });// To disable model validation on delete, set validateBeforeDelete option to false
PetSchema.plugin(mongooseDelete, { validateBeforeDelete: false });
`This is based on existing Mongoose validateBeforeSave option
$3
`typescript
// Index only specific fields (default)
PetSchema.plugin(mongooseDelete, { indexFields: ['deleted'] });
// or
PetSchema.plugin(mongooseDelete, { indexFields: ['deleted', 'deletedAt'] });// Index all field related to plugin (deleted, deletedAt, deletedBy)
PetSchema.plugin(mongooseDelete, { indexFields: true });
`$3
`typescript
type PetDocument = Document & DeletedDocument & DeletedAtDocument & DeletedByDocument & { name?: string };
type PetModel = Model & DeletedModel & DeletedByModel;const PetSchema = new Schema({
name: String
});
// Add a custom name for each property, will create alias for the original name (deletedBy/deletedAt)
PetSchema.plugin(mongooseDelete, { deletedBy: 'deleted_by', deletedAt: 'deleted_at' });
// Use custom schema type definition by supplying an object
PetSchema.plugin(mongooseDelete, { deletedBy: { name: 'deleted_by', type: String }, deletedAt: { name: 'deleted_at' } });
`
Expects a Mongoose Schema Types object with the added option of name`.The MIT License
Copyright (c) 2024 Stanislav Protaschuk
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.