Skip to content

Commit

Permalink
Merge branch '5.x' of github.com:Automattic/mongoose into 5.x
Browse files Browse the repository at this point in the history
  • Loading branch information
vkarpov15 committed Apr 4, 2023
2 parents eeabe5f + 14464d1 commit 3f827b3
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 8 deletions.
37 changes: 29 additions & 8 deletions lib/helpers/update/removeUnusedArrayFilters.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,33 @@
*/

module.exports = function removeUnusedArrayFilters(update, arrayFilters) {
const updateKeys = Object.keys(update).map(key => Object.keys(update[key])).reduce((cur, arr) => cur.concat(arr), []);
return arrayFilters.filter(obj => {
const firstKey = Object.keys(obj)[0];
const firstDot = firstKey.indexOf('.');
const arrayFilterKey = firstDot === -1 ? firstKey : firstKey.slice(0, firstDot);

return updateKeys.find(key => key.includes('$[' + arrayFilterKey + ']')) != null;
const updateKeys = Object.keys(update)
.map((key) => Object.keys(update[key]))
.reduce((cur, arr) => cur.concat(arr), []);
return arrayFilters.filter((obj) => {
return _checkSingleFilterKey(obj, updateKeys);
});
};
};

function _checkSingleFilterKey(arrayFilter, updateKeys) {
const firstKey = Object.keys(arrayFilter)[0];

if (firstKey === '$and' || firstKey === '$or') {
if (!Array.isArray(arrayFilter[firstKey])) {
return false;
}
return (
arrayFilter[firstKey].find((filter) =>
_checkSingleFilterKey(filter, updateKeys)
) != null
);
}

const firstDot = firstKey.indexOf('.');
const arrayFilterKey =
firstDot === -1 ? firstKey : firstKey.slice(0, firstDot);

return (
updateKeys.find((key) => key.includes('$[' + arrayFilterKey + ']')) != null
);
}
19 changes: 19 additions & 0 deletions test/helpers/update.removeUnusedArrayFilters.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
'use strict';

const assert = require('assert');
const removeUnusedArrayFilters = require('../../lib/helpers/update/removeUnusedArrayFilters');

describe('removeUnusedArrayFilters', function() {
it('respects `$or` (gh-10696)', function() {
const update = {
$set: {
'requests.$[i].status.aa': 'ON_GOING',
'requests.$[i].status.bb': 'ON_GOING'
}
};
const arrayFilters = [{ $or: [{ 'i.no': 1 }] }];

const ret = removeUnusedArrayFilters(update, arrayFilters);
assert.deepEqual(ret, [{ $or: [{ 'i.no': 1 }] }]);
});
});

0 comments on commit 3f827b3

Please sign in to comment.