UNPKG

1.66 kBJavaScriptView Raw
1'use strict';
2
3const objectIdSymbol = require('../helpers/symbols').objectIdSymbol;
4const utils = require('../utils');
5
6/*!
7 * ignore
8 */
9
10module.exports = function shardingPlugin(schema) {
11 schema.post('init', function() {
12 storeShard.call(this);
13 return this;
14 });
15 schema.pre('save', function(next) {
16 applyWhere.call(this);
17 next();
18 });
19 schema.pre('remove', function(next) {
20 applyWhere.call(this);
21 next();
22 });
23 schema.post('save', function() {
24 storeShard.call(this);
25 });
26};
27
28/*!
29 * ignore
30 */
31
32function applyWhere() {
33 let paths;
34 let len;
35
36 if (this.$__.shardval) {
37 paths = Object.keys(this.$__.shardval);
38 len = paths.length;
39
40 this.$where = this.$where || {};
41 for (let i = 0; i < len; ++i) {
42 this.$where[paths[i]] = this.$__.shardval[paths[i]];
43 }
44 }
45}
46
47/*!
48 * ignore
49 */
50
51module.exports.storeShard = storeShard;
52
53/*!
54 * ignore
55 */
56
57function storeShard() {
58 // backwards compat
59 const key = this.schema.options.shardKey || this.schema.options.shardkey;
60 if (!utils.isPOJO(key)) {
61 return;
62 }
63
64 const orig = this.$__.shardval = {};
65 const paths = Object.keys(key);
66 const len = paths.length;
67 let val;
68
69 for (let i = 0; i < len; ++i) {
70 val = this.$__getValue(paths[i]);
71 if (val == null) {
72 orig[paths[i]] = val;
73 } else if (utils.isMongooseObject(val)) {
74 orig[paths[i]] = val.toObject({ depopulate: true, _isNested: true });
75 } else if (val instanceof Date || val[objectIdSymbol]) {
76 orig[paths[i]] = val;
77 } else if (typeof val.valueOf === 'function') {
78 orig[paths[i]] = val.valueOf();
79 } else {
80 orig[paths[i]] = val;
81 }
82 }
83}