@@ -144,16 +144,29 @@ module.exports = function (schema, options) {
144144 schema . pre ( 'aggregate' , function ( ) {
145145 var firstMatch = this . pipeline ( ) [ 0 ] ;
146146
147- if ( firstMatch . $match ?. deleted ?. $ne !== false ) {
148- if ( firstMatch . $match ?. showAllDocuments === 'true' ) {
149- var { showAllDocuments, ...replacement } = firstMatch . $match ;
150- this . pipeline ( ) . shift ( ) ;
151- if ( Object . keys ( replacement ) . length > 0 ) {
152- this . pipeline ( ) . unshift ( { $match : replacement } ) ;
153- }
154- } else {
155- this . pipeline ( ) . unshift ( { $match : { deleted : { '$ne' : true } } } ) ;
147+ var hasDeletedMatchStage = typeof firstMatch . $match ?. deleted !== 'undefined'
148+ var shouldShowAllDocuments = firstMatch . $match ?. showAllDocuments === true
149+
150+ if ( hasDeletedMatchStage || shouldShowAllDocuments ) {
151+ var { showAllDocuments, ...replacement } = firstMatch . $match ;
152+ this . pipeline ( ) . shift ( ) ;
153+ if ( Object . keys ( replacement ) . length > 0 ) {
154+ this . pipeline ( ) . unshift ( {
155+ $match : replacement
156+ } ) ;
156157 }
158+ } else if ( ! hasDeletedMatchStage && use$neOperator ) {
159+ this . pipeline ( ) . unshift ( {
160+ $match : {
161+ deleted : { '$ne' : true }
162+ }
163+ } ) ;
164+ } else if ( ! hasDeletedMatchStage && ! use$neOperator ) {
165+ this . pipeline ( ) . unshift ( {
166+ $match : {
167+ deleted : false
168+ }
169+ } ) ;
157170 }
158171 } ) ;
159172 }
@@ -204,7 +217,7 @@ module.exports = function (schema, options) {
204217 schema . statics [ method + 'WithDeleted' ] = function ( ) {
205218 var args = [ ] ;
206219 Array . prototype . push . apply ( args , arguments ) ;
207- var match = { $match : { showAllDocuments : ' true' } } ;
220+ var match = { $match : { showAllDocuments : true } } ;
208221 arguments . length ? args [ 0 ] . unshift ( match ) : args . push ( [ match ] ) ;
209222 return Model [ method ] . apply ( this , args ) ;
210223 } ;
0 commit comments