All files / mongoose/lib/plugins sharding.js

37.5% Statements 15/40
22.22% Branches 4/18
71.42% Functions 5/7
39.47% Lines 15/38

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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84    1x 1x           1x 8x       8x 17x 17x   8x       8x 13x                       17x                             1x               13x 13x 13x                                              
'use strict';
 
const objectIdSymbol = require('../helpers/symbols').objectIdSymbol;
const utils = require('../utils');
 
/*!
 * ignore
 */
 
module.exports = function shardingPlugin(schema) {
  schema.post('init', function shardingPluginPostInit() {
    storeShard.call(this);
    return this;
  });
  schema.pre('save', function shardingPluginPreSave(next) {
    applyWhere.call(this);
    next();
  });
  schema.pre('remove', function shardingPluginPreRemove(next) {
    applyWhere.call(this);
    next();
  });
  schema.post('save', function shardingPluginPostSave() {
    storeShard.call(this);
  });
};
 
/*!
 * ignore
 */
 
function applyWhere() {
  let paths;
  let len;
 
  Iif (this.$__.shardval) {
    paths = Object.keys(this.$__.shardval);
    len = paths.length;
 
    this.$where = this.$where || {};
    for (let i = 0; i < len; ++i) {
      this.$where[paths[i]] = this.$__.shardval[paths[i]];
    }
  }
}
 
/*!
 * ignore
 */
 
module.exports.storeShard = storeShard;
 
/*!
 * ignore
 */
 
function storeShard() {
  // backwards compat
  const key = this.$__schema.options.shardKey || this.$__schema.options.shardkey;
  Eif (!utils.isPOJO(key)) {
    return;
  }
 
  const orig = this.$__.shardval = {};
  const paths = Object.keys(key);
  const len = paths.length;
  let val;
 
  for (let i = 0; i < len; ++i) {
    val = this.$__getValue(paths[i]);
    if (val == null) {
      orig[paths[i]] = val;
    } else if (utils.isMongooseObject(val)) {
      orig[paths[i]] = val.toObject({ depopulate: true, _isNested: true });
    } else if (val instanceof Date || val[objectIdSymbol]) {
      orig[paths[i]] = val;
    } else if (typeof val.valueOf === 'function') {
      orig[paths[i]] = val.valueOf();
    } else {
      orig[paths[i]] = val;
    }
  }
}