@@ -182,15 +182,7 @@ module.exports = function getModelsMapForPopulate(model, docs, options) {
182
182
if ( hasMatchFunction ) {
183
183
match = match . call ( doc , doc ) ;
184
184
}
185
- if ( Array . isArray ( match ) ) {
186
- for ( const item of match ) {
187
- if ( item != null && item . $where ) {
188
- throw new MongooseError ( 'Cannot use $where filter with populate() match' ) ;
189
- }
190
- }
191
- } else if ( match != null && match . $where != null ) {
192
- throw new MongooseError ( 'Cannot use $where filter with populate() match' ) ;
193
- }
185
+ throwOn$where ( match ) ;
194
186
data . match = match ;
195
187
data . hasMatchFunction = hasMatchFunction ;
196
188
data . isRefPath = isRefPath ;
@@ -469,15 +461,7 @@ function _virtualPopulate(model, docs, options, _virtualRes) {
469
461
data . match = match ;
470
462
data . hasMatchFunction = hasMatchFunction ;
471
463
472
- if ( Array . isArray ( match ) ) {
473
- for ( const item of match ) {
474
- if ( item != null && item . $where ) {
475
- throw new MongooseError ( 'Cannot use $where filter with populate() match' ) ;
476
- }
477
- }
478
- } else if ( match != null && match . $where != null ) {
479
- throw new MongooseError ( 'Cannot use $where filter with populate() match' ) ;
480
- }
464
+ throwOn$where ( match ) ;
481
465
482
466
// Get local fields
483
467
const ret = _getLocalFieldValues ( doc , localField , model , options , virtual ) ;
@@ -749,3 +733,24 @@ function _findRefPathForDiscriminators(doc, modelSchema, data, options, normaliz
749
733
750
734
return modelNames ;
751
735
}
736
+
737
+ /**
738
+ * Throw an error if there are any $where keys
739
+ */
740
+
741
+ function throwOn$where ( match ) {
742
+ if ( match == null ) {
743
+ return ;
744
+ }
745
+ if ( typeof match !== 'object' ) {
746
+ return ;
747
+ }
748
+ for ( const key of Object . keys ( match ) ) {
749
+ if ( key === '$where' ) {
750
+ throw new MongooseError ( 'Cannot use $where filter with populate() match' ) ;
751
+ }
752
+ if ( match [ key ] != null && typeof match [ key ] === 'object' ) {
753
+ throwOn$where ( match [ key ] ) ;
754
+ }
755
+ }
756
+ }
0 commit comments