summaryrefslogtreecommitdiffstats
path: root/node_modules/mongoose/lib/plugins/sharding.js
blob: 560053ed30c5cfda200a53dbb8fb51c70999a127 (plain) (blame)
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
'use strict';

const objectIdSymbol = require('../helpers/symbols').objectIdSymbol;
const utils = require('../utils');

/*!
 * ignore
 */

module.exports = function shardingPlugin(schema) {
  schema.post('init', function() {
    storeShard.call(this);
    return this;
  });
  schema.pre('save', function(next) {
    applyWhere.call(this);
    next();
  });
  schema.pre('remove', function(next) {
    applyWhere.call(this);
    next();
  });
  schema.post('save', function() {
    storeShard.call(this);
  });
};

/*!
 * ignore
 */

function applyWhere() {
  let paths;
  let len;

  if (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;
  if (!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;
    }
  }
}