removeUnusedArrayFilters.js 1.1 KB

1234567891011121314151617181920212223242526272829303132
  1. 'use strict';
  2. /**
  3. * MongoDB throws an error if there's unused array filters. That is, if `options.arrayFilters` defines
  4. * a filter, but none of the `update` keys use it. This should be enough to filter out all unused array
  5. * filters.
  6. */
  7. module.exports = function removeUnusedArrayFilters(update, arrayFilters) {
  8. const updateKeys = Object.keys(update).
  9. map(key => Object.keys(update[key])).
  10. reduce((cur, arr) => cur.concat(arr), []);
  11. return arrayFilters.filter(obj => {
  12. return _checkSingleFilterKey(obj, updateKeys);
  13. });
  14. };
  15. function _checkSingleFilterKey(arrayFilter, updateKeys) {
  16. const firstKey = Object.keys(arrayFilter)[0];
  17. if (firstKey === '$and' || firstKey === '$or') {
  18. if (!Array.isArray(arrayFilter[firstKey])) {
  19. return false;
  20. }
  21. return arrayFilter[firstKey].find(filter => _checkSingleFilterKey(filter, updateKeys)) != null;
  22. }
  23. const firstDot = firstKey.indexOf('.');
  24. const arrayFilterKey = firstDot === -1 ? firstKey : firstKey.slice(0, firstDot);
  25. return updateKeys.find(key => key.includes('$[' + arrayFilterKey + ']')) != null;
  26. }