All files / mongoose/lib/helpers/update removeUnusedArrayFilters.js

6.25% Statements 1/16
0% Branches 0/8
0% Functions 0/7
7.14% Lines 1/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33                1x                                                
'use strict';
 
/**
 * MongoDB throws an error if there's unused array filters. That is, if `options.arrayFilters` defines
 * a filter, but none of the `update` keys use it. This should be enough to filter out all unused array
 * filters.
 */
 
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 => {
    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;
}