@@ -4054,6 +4054,25 @@ describe('Query', function() {
40544054 } ) ;
40554055 } ) ;
40564056
4057+ it ( 'shallow clones $and, $or if merging with empty filter (gh-14567) (gh-12944)' , function ( ) {
4058+ const TestModel = db . model (
4059+ 'Test' ,
4060+ Schema ( { name : String , age : Number , active : Boolean } )
4061+ ) ;
4062+
4063+ let originalQuery = { $and : [ { active : true } ] } ;
4064+ let q = TestModel . countDocuments ( originalQuery )
4065+ . and ( [ { age : { $gte : 18 } } ] ) ;
4066+ assert . deepStrictEqual ( originalQuery , { $and : [ { active : true } ] } ) ;
4067+ assert . deepStrictEqual ( q . getFilter ( ) , { $and : [ { active : true } , { age : { $gte : 18 } } ] } ) ;
4068+
4069+ originalQuery = { $or : [ { active : true } ] } ;
4070+ q = TestModel . countDocuments ( originalQuery )
4071+ . or ( [ { age : { $gte : 18 } } ] ) ;
4072+ assert . deepStrictEqual ( originalQuery , { $or : [ { active : true } ] } ) ;
4073+ assert . deepStrictEqual ( q . getFilter ( ) , { $or : [ { active : true } , { age : { $gte : 18 } } ] } ) ;
4074+ } ) ;
4075+
40574076 it ( 'should avoid sending empty session to MongoDB server (gh-13052)' , async function ( ) {
40584077 const m = new mongoose . Mongoose ( ) ;
40594078
@@ -4236,4 +4255,22 @@ describe('Query', function() {
42364255 q . sort ( { } , { override : true } ) ;
42374256 assert . deepStrictEqual ( q . getOptions ( ) . sort , { } ) ;
42384257 } ) ;
4258+
4259+ it ( 'avoids mutating user-provided query selectors (gh-14567)' , async function ( ) {
4260+ const TestModel = db . model (
4261+ 'Test' ,
4262+ Schema ( { name : String , age : Number , active : Boolean } )
4263+ ) ;
4264+
4265+ await TestModel . create ( { name : 'John' , age : 21 } ) ;
4266+ await TestModel . create ( { name : 'Bob' , age : 35 } ) ;
4267+
4268+ const adultQuery = { age : { $gte : 18 } } ;
4269+
4270+ const docs = await TestModel . find ( adultQuery ) . where ( 'age' ) . lte ( 25 ) ;
4271+ assert . equal ( docs . length , 1 ) ;
4272+ assert . equal ( docs [ 0 ] . name , 'John' ) ;
4273+
4274+ assert . deepStrictEqual ( adultQuery , { age : { $gte : 18 } } ) ;
4275+ } ) ;
42394276} ) ;
0 commit comments