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

@stenneepro/mongoose-soft-delete

v1.2.0

Published

Mongoose soft delete plugin

Downloads

14

Readme

Mongoose 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.

Build Status

Features

Installation

Install using npm

npm install @stenneepro/mongoose-soft-delete

Usage

We can use this plugin with or without options.

Simple usage

import mongooseDelete, { DeletedDocument, DeletedModel, DeletedQuery } from '@stenneepro/mongoose-soft-delete';

type PetDocument = Document & DeletedDocument & { name?: string };
type PetModel = Model<PetDocument, DeletedQuery> & DeletedModel<PetDocument>;

const PetSchema = new Schema<PetDocument, PetModel>({
	name: String
});

PetSchema.plugin(mongooseDelete);

const Pet = mongoose.model<PetModel, PetDocument>('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' }

Save time of deletion

import mongooseDelete, { DeletedDocument, DeletedAtDocument, DeletedModel, DeletedQuery } from '@stenneepro/mongoose-soft-delete';

type PetDocument = Document & DeletedDocument & DeletedAtDocument & { name?: string };
type PetModel = Model<PetDocument, DeletedQuery> & DeletedModel<PetDocument>;

const PetSchema = new Schema<PetDocument, PetModel>({
	name: String
});

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

const Pet = mongoose.model<PetDocument, PetModel>('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' }

Who has deleted the data?

import mongooseDelete, { DeletedDocument, DeletedByDocument, DeletedModel, DeletedByModel, DeletedQuery } from '@stenneepro/mongoose-soft-delete';

type PetDocument = Document & DeletedDocument & DeletedByDocument & { name?: string };
type PetModel = Model<PetDocument, DeletedQuery> & DeletedModel<PetDocument> & DeletedByModel<PetDocument>;

const PetSchema = new Schema<PetDocument, PetModel>({
    name: String
});

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

const Pet = mongoose.model<PetDocument, PetModel>('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.

import mongooseDelete, { DeletedDocument, DeletedByDocument, DeletedModel, DeletedByModel, DeletedQuery } from '@stenneepro/mongoose-soft-delete';

type PetDocument = Document & DeletedDocument & DeletedByDocument<string> & { name?: string };
type PetModel = Model<PetDocument, DeletedQuery> & DeletedModel<PetDocument> & DeletedByModel<PetDocument, string>;

const PetSchema = new Schema<PetDocument, PetModel>({
	name: String
});

PetSchema.plugin(mongooseDelete, { deletedBy: { type: String } });

const Pet = mongoose.model<PetDocument, PetModel>('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

Document types

| Type | Adds property | Adds method | --- | --- | --- | DeletedDocument | document.deleted | document.deleteOne(), document.restoreOne() | DeletedAtDocument | document.deletedAt | | DeletedByDocument<TUser, TDeletedBy = TUser> | document.deletedBy | document.deleteOneByUser(...)

Model types

| Type | Adds static methods | --- | --- | DeletedModel<T> | Model.deleteOne(...), Model.deleteMany(...), Model.restoreOne(...), Model.restoreMany(...) | DeletedByModel<T, TUser> | Model.deleteOneByUser(...), Model.deleteManyByUser(...)

Query helper types

| Type | Adds query helpers | --- | --- | DeletedQuery<T> | notDeleted(), onlyDeleted(), withDeleted()

Bulk delete and restore

// 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 });

Method overridden

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 }) |

Examples how to override one or multiple methods

// Override all methods (default)
PetSchema.plugin(mongooseDelete, { overrideMethods: true });

// Overide only specific methods
PetSchema.plugin(mongooseDelete, { overrideMethods: ['count', 'find', 'findOne'] });

Example of usage overridden methods

// 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();

Disable model validation on delete

// 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

Create index on fields

// 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 });

Custom field names or schema type definition

type PetDocument = Document & DeletedDocument & DeletedAtDocument & DeletedByDocument<string> & { name?: string };
type PetModel = Model<PetDocument, DeletedQuery> & DeletedModel<PetDocument> & DeletedByModel<PetDocument, string>;

const PetSchema = new Schema<PetDocument, PetModel>({
	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.

License

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.