@@ -8259,6 +8259,58 @@ describe('model: populate:', function() {
8259
8259
assert . deepEqual ( populatedRides [ 1 ] . files , [ ] ) ;
8260
8260
} ) ;
8261
8261
8262
+ it ( 'doesnt insert empty document when lean populating a path within an underneath non-existent document array (gh-14098)' , async function ( ) {
8263
+ const userSchema = new mongoose . Schema ( {
8264
+ fullName : String ,
8265
+ company : String
8266
+ } ) ;
8267
+ const User = db . model ( 'User' , userSchema ) ;
8268
+
8269
+ const fileSchema = new mongoose . Schema ( {
8270
+ _id : String ,
8271
+ uploaderId : {
8272
+ type : mongoose . ObjectId ,
8273
+ ref : 'User'
8274
+ }
8275
+ } , { toObject : { virtuals : true } , toJSON : { virtuals : true } } ) ;
8276
+ fileSchema . virtual ( 'uploadedBy' , {
8277
+ ref : 'User' ,
8278
+ localField : 'uploaderId' ,
8279
+ foreignField : '_id' ,
8280
+ justOne : true
8281
+ } ) ;
8282
+
8283
+ const contentSchema = new mongoose . Schema ( {
8284
+ memo : String ,
8285
+ files : { type : [ fileSchema ] , default : [ ] }
8286
+ } , { toObject : { virtuals : true } , toJSON : { virtuals : true } , _id : false } ) ;
8287
+
8288
+ const postSchema = new mongoose . Schema ( {
8289
+ title : String ,
8290
+ content : { type : contentSchema }
8291
+ } , { toObject : { virtuals : true } , toJSON : { virtuals : true } } ) ;
8292
+ const Post = db . model ( 'Test1' , postSchema ) ;
8293
+
8294
+ const user = await User . create ( { fullName : 'John Doe' , company : 'GitHub' } ) ;
8295
+ await Post . create ( [
8296
+ { title : 'London-Paris' } ,
8297
+ {
8298
+ title : 'Berlin-Moscow' ,
8299
+ content : {
8300
+ memo : 'Not Easy' ,
8301
+ files : [ { _id : '123' , uploaderId : user . _id } ]
8302
+ }
8303
+ }
8304
+ ] ) ;
8305
+ await Post . updateMany ( { } , { $unset : { 'content.files' : 1 } } ) ;
8306
+ const populatedRides = await Post . find ( { } ) . populate ( {
8307
+ path : 'content.files.uploadedBy' ,
8308
+ justOne : true
8309
+ } ) . lean ( ) ;
8310
+ assert . equal ( populatedRides [ 0 ] . content . files , undefined ) ;
8311
+ assert . equal ( populatedRides [ 1 ] . content . files , undefined ) ;
8312
+ } ) ;
8313
+
8262
8314
it ( 'sets empty array if populating undefined path (gh-8455)' , async function ( ) {
8263
8315
const TestSchema = new Schema ( {
8264
8316
thingIds : [ mongoose . ObjectId ]
0 commit comments