@@ -10968,4 +10968,57 @@ describe('model: populate:', function() {
1096810968 assert . equal ( res . children [ 0 ] . subdoc . name , 'A' ) ;
1096910969 assert . equal ( res . children [ 1 ] . subdoc . name , 'B' ) ;
1097010970 } ) ;
10971+
10972+ it ( 'avoids filtering out `null` values when applying match function (gh-14494)' , async function ( ) {
10973+ const gradeSchema = new mongoose . Schema ( {
10974+ studentId : mongoose . Types . ObjectId ,
10975+ classId : mongoose . Types . ObjectId ,
10976+ grade : String
10977+ } ) ;
10978+
10979+ const Grade = db . model ( 'Test' , gradeSchema ) ;
10980+
10981+ const studentSchema = new mongoose . Schema ( {
10982+ name : String
10983+ } ) ;
10984+
10985+ studentSchema . virtual ( 'grade' , {
10986+ ref : Grade ,
10987+ localField : '_id' ,
10988+ foreignField : 'studentId' ,
10989+ match : ( doc ) => ( {
10990+ classId : doc . _id
10991+ } ) ,
10992+ justOne : true
10993+ } ) ;
10994+
10995+ const classSchema = new mongoose . Schema ( {
10996+ name : String ,
10997+ students : [ studentSchema ]
10998+ } ) ;
10999+
11000+ const Class = db . model ( 'Test2' , classSchema ) ;
11001+
11002+ const newClass = await Class . create ( {
11003+ name : 'History' ,
11004+ students : [ { name : 'Henry' } , { name : 'Robert' } ]
11005+ } ) ;
11006+
11007+ const studentRobert = newClass . students . find (
11008+ ( { name } ) => name === 'Robert'
11009+ ) ;
11010+
11011+ await Grade . create ( {
11012+ studentId : studentRobert . _id ,
11013+ classId : newClass . _id ,
11014+ grade : 'B'
11015+ } ) ;
11016+
11017+ const latestClass = await Class . findOne ( { name : 'History' } ) . populate ( 'students.grade' ) ;
11018+
11019+ assert . equal ( latestClass . students [ 0 ] . name , 'Henry' ) ;
11020+ assert . equal ( latestClass . students [ 0 ] . grade , null ) ;
11021+ assert . equal ( latestClass . students [ 1 ] . name , 'Robert' ) ;
11022+ assert . equal ( latestClass . students [ 1 ] . grade . grade , 'B' ) ;
11023+ } ) ;
1097111024} ) ;
0 commit comments