1- import mongoose , { CallbackError , SaveOptions } from 'mongoose' ;
1+ import mongoose , { CallbackError , MongooseQueryMiddleware , SaveOptions } from 'mongoose' ;
2+
3+ const QUERY_HOOK_METHODS : MongooseQueryMiddleware [ ] = [
4+ 'find' ,
5+ 'findOne' ,
6+ 'count' ,
7+ 'countDocuments' ,
8+ 'updateMany' ,
9+ 'updateOne' ,
10+ 'findOneAndUpdate' ,
11+ 'distinct' ,
12+ ] ;
213
314export const softDeletePlugin = ( schema : mongoose . Schema ) => {
415 schema . add ( {
@@ -14,7 +25,7 @@ export const softDeletePlugin = (schema: mongoose.Schema) => {
1425 } ) ;
1526
1627 // @ts -ignore
17- schema . pre ( 'find' ,
28+ schema . pre ( QUERY_HOOK_METHODS ,
1829 async function ( this , next : ( err ?: CallbackError ) => void ) {
1930 if ( this . getFilter ( ) . isDeleted === true ) {
2031 return next ( ) ;
@@ -24,26 +35,6 @@ export const softDeletePlugin = (schema: mongoose.Schema) => {
2435 } ,
2536 ) ;
2637
27- // @ts -ignore
28- schema . pre ( 'count' ,
29- async function ( this , next : ( err ?: CallbackError ) => void ) {
30- if ( this . getFilter ( ) . isDeleted === true ) {
31- return next ( ) ;
32- }
33- this . setQuery ( { ...this . getFilter ( ) , isDeleted : { $ne : true } } ) ;
34- next ( ) ;
35- } )
36-
37- // @ts -ignore
38- schema . pre ( 'countDocuments' ,
39- async function ( this , next : ( err ?: CallbackError ) => void ) {
40- if ( this . getFilter ( ) . isDeleted === true ) {
41- return next ( ) ;
42- }
43- this . setQuery ( { ...this . getFilter ( ) , isDeleted : { $ne : true } } ) ;
44- next ( ) ;
45- } )
46-
4738 schema . static ( 'findDeleted' , async function ( ) {
4839 return this . find ( { isDeleted : true } ) ;
4940 } ) ;
0 commit comments