@@ -25,19 +25,16 @@ export const softDeletePlugin = (schema: mongoose.Schema) => {
2525 } ,
2626 } ) ;
2727
28- // Add query middleware to filter out soft deleted documents
29- QUERY_HOOK_METHODS . forEach ( method => {
30- schema . pre ( method , function ( next ) {
31- const filter = this . getFilter ( ) ;
32- if ( filter . isDeleted === true ) {
28+ // @ts -ignore
29+ schema . pre ( QUERY_HOOK_METHODS ,
30+ async function ( this , next : ( err ?: CallbackError ) => void ) {
31+ if ( this . getFilter ( ) . isDeleted === true ) {
3332 return next ( ) ;
3433 }
35- // Modify the filter to exclude soft deleted documents
36- const newFilter = { ...filter , isDeleted : { $ne : true } } ;
37- this . setQuery ( newFilter ) ;
34+ this . setQuery ( { ...this . getFilter ( ) , isDeleted : { $ne : true } } ) ;
3835 next ( ) ;
39- } ) ;
40- } ) ;
36+ } ,
37+ ) ;
4138
4239 schema . pre ( 'aggregate' , function ( next ) {
4340 if ( this . options . skipHook ) return next ( ) ;
@@ -50,19 +47,21 @@ export const softDeletePlugin = (schema: mongoose.Schema) => {
5047 } ) ;
5148
5249 schema . static ( 'restore' , async function ( query ) {
50+
5351 // add {isDeleted: true} because the method find is set to filter the non deleted documents only,
5452 // so if we don't add {isDeleted: true}, it won't be able to find it
5553 const updatedQuery = {
5654 ...query ,
5755 isDeleted : true
5856 } ;
5957 const deletedTemplates = await this . find ( updatedQuery ) ;
60- if ( ! deletedTemplates || deletedTemplates . length === 0 ) {
61- return { restored : 0 } ;
58+ if ( ! deletedTemplates ) {
59+ return Error ( 'element not found' ) ;
6260 }
6361 let restored = 0 ;
6462 for ( const deletedTemplate of deletedTemplates ) {
6563 if ( deletedTemplate . isDeleted ) {
64+ deletedTemplate . $isDeleted ( false ) ;
6665 deletedTemplate . isDeleted = false ;
6766 deletedTemplate . deletedAt = null ;
6867 await deletedTemplate . save ( ) . then ( ( ) => restored ++ ) . catch ( ( e : mongoose . Error ) => { throw new Error ( e . name + ' ' + e . message ) } ) ;
@@ -73,12 +72,13 @@ export const softDeletePlugin = (schema: mongoose.Schema) => {
7372
7473 schema . static ( 'softDelete' , async function ( query , options ?: SaveOptions ) {
7574 const templates = await this . find ( query ) ;
76- if ( ! templates || templates . length === 0 ) {
77- return { deleted : 0 } ;
75+ if ( ! templates ) {
76+ return Error ( 'Element not found' ) ;
7877 }
7978 let deleted = 0 ;
8079 for ( const template of templates ) {
8180 if ( ! template . isDeleted ) {
81+ template . $isDeleted ( true ) ;
8282 template . isDeleted = true ;
8383 template . deletedAt = new Date ( ) ;
8484 await template . save ( options ) . then ( ( ) => deleted ++ ) . catch ( ( e : mongoose . Error ) => { throw new Error ( e . name + ' ' + e . message ) } ) ;
0 commit comments