@@ -182,15 +182,7 @@ module.exports = function getModelsMapForPopulate(model, docs, options) {
182182    if  ( hasMatchFunction )  { 
183183      match  =  match . call ( doc ,  doc ) ; 
184184    } 
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 ) ; 
194186    data . match  =  match ; 
195187    data . hasMatchFunction  =  hasMatchFunction ; 
196188    data . isRefPath  =  isRefPath ; 
@@ -469,15 +461,7 @@ function _virtualPopulate(model, docs, options, _virtualRes) {
469461    data . match  =  match ; 
470462    data . hasMatchFunction  =  hasMatchFunction ; 
471463
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 ) ; 
481465
482466    // Get local fields 
483467    const  ret  =  _getLocalFieldValues ( doc ,  localField ,  model ,  options ,  virtual ) ; 
@@ -749,3 +733,24 @@ function _findRefPathForDiscriminators(doc, modelSchema, data, options, normaliz
749733
750734  return  modelNames ; 
751735} 
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