Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

sharding.js 1.7KB

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