Skip to content

Commit

Permalink
BREAKING CHANGE: merge $and, $or conditions in query filters
Browse files Browse the repository at this point in the history
Fix #12944
  • Loading branch information
vkarpov15 committed Feb 17, 2023
1 parent 38a8d2c commit 8850b75
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
19 changes: 19 additions & 0 deletions lib/query.js
Original file line number Diff line number Diff line change
Expand Up @@ -2359,6 +2359,15 @@ Query.prototype.merge = function(source) {
// if source has a feature, apply it to ourselves

if (source._conditions) {
opts.omit = {};
if (this._conditions?.$and && source._conditions.$and) {
opts.omit['$and'] = true;
this._conditions.$and = this._conditions.$and.concat(source._conditions.$and);
}
if (this._conditions?.$or && source._conditions.$or) {
opts.omit['$or'] = true;
this._conditions.$or = this._conditions.$or.concat(source._conditions.$or);
}
utils.merge(this._conditions, source._conditions, opts);
}

Expand Down Expand Up @@ -2390,6 +2399,16 @@ Query.prototype.merge = function(source) {
return this;
}

opts.omit = {};
if (this._conditions?.$and && source.$and) {
opts.omit['$and'] = true;
this._conditions.$and = this._conditions.$and.concat(source.$and);
}
if (this._conditions?.$or && source.$or) {
opts.omit['$or'] = true;
this._conditions.$or = this._conditions.$or.concat(source.$or);
}

// plain object
utils.merge(this._conditions, source, opts);

Expand Down
18 changes: 18 additions & 0 deletions test/query.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4323,4 +4323,22 @@ describe('Query', function() {

assert.strictEqual(books.length, 0);
});

it('merges $and, $or conditions (gh-12944)', function() {
const Test = db.model('Test', new Schema({ tags: [String] }));

let q = Test.find({ $and: [{ tags: 'a' }] });
q.find({ $and: [{ tags: 'b' }] });
q.find({ $and: [{ tags: 'c' }] });

assert.deepEqual(q.getFilter(), {
$and: [{ tags: 'a' }, { tags: 'b' }, { tags: 'c' }]
});

q = Test.find({ $or: [{ tags: 'a' }] });
q.find({ $or: [{ tags: 'b' }] });
assert.deepEqual(q.getFilter(), {
$or: [{ tags: 'a' }, { tags: 'b' }]
});
});
});

0 comments on commit 8850b75

Please sign in to comment.