Package: mongoose-soft-deleting
Package for operating soft delete on mongoose models
Install
npm i mongoose-soft-deleting
Usage
By default the plugin include two new fields in the schema to which you want to apply it: _deleted, _deletedAt. Which answer to the questions 'Is the document deleted ?' and 'When has been the document deleted ?'. Optionally you can specify a _deletedBy field too to answer the question 'Who deleted it?'.
The package provide a middleware hook too for intercepting the pre soft deleting.
Example without user
const softDeletePlugin = ; // ... const TestSchema = A: type: String default: 'A' B: type: String default: 'B' ; TestSchema; const TestModel = mongoose; // ... // Pre save TestSchema // ... const doc = await TestModel; // To soft delete await doc; // To restore from soft delete await doc; // To completely remove: call it twice await doc; await doc; // or await doc; // To know if it is deleted const isDeleted = doc || doc_deleted; // To know when const deletedAt = doc_deletedAt;
Example with user
const softDeletePlugin = ; // ... const TestSchema = A: type: String default: 'A' B: type: String default: 'B' ; const UserTestSchema = name: type: String default: 'Name' password: type: String default: '🤫' ; TestSchema; const TestModel = mongoose;const UserTestModel = mongoose; // ... const user = UserTestModel;const test = TestModel; test;
Test
You can try the tests using the following command ( before you need to change the connection to MongoDB ) :
npm run test