sharding.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 shardingPluginPostInit() {
  9. storeShard.call(this);
  10. return this;
  11. });
  12. schema.pre('save', function shardingPluginPreSave() {
  13. applyWhere.call(this);
  14. });
  15. schema.pre('deleteOne', { document: true, query: false }, function shardingPluginPreDeleteOne() {
  16. applyWhere.call(this);
  17. });
  18. schema.pre('updateOne', { document: true, query: false }, function shardingPluginPreUpdateOne() {
  19. applyWhere.call(this);
  20. });
  21. schema.post('save', function shardingPluginPostSave() {
  22. storeShard.call(this);
  23. });
  24. };
  25. /*!
  26. * ignore
  27. */
  28. function applyWhere() {
  29. let paths;
  30. let len;
  31. if (this.$__.shardval) {
  32. paths = Object.keys(this.$__.shardval);
  33. len = paths.length;
  34. this.$where = this.$where || {};
  35. for (let i = 0; i < len; ++i) {
  36. this.$where[paths[i]] = this.$__.shardval[paths[i]];
  37. }
  38. }
  39. }
  40. /*!
  41. * ignore
  42. */
  43. module.exports.storeShard = storeShard;
  44. /*!
  45. * ignore
  46. */
  47. function storeShard() {
  48. // backwards compat
  49. const key = this.$__schema.options.shardKey || this.$__schema.options.shardkey;
  50. if (!utils.isPOJO(key)) {
  51. return;
  52. }
  53. const orig = this.$__.shardval = {};
  54. const paths = Object.keys(key);
  55. const len = paths.length;
  56. let val;
  57. for (let i = 0; i < len; ++i) {
  58. val = this.$__getValue(paths[i]);
  59. if (val == null) {
  60. orig[paths[i]] = val;
  61. } else if (utils.isMongooseObject(val)) {
  62. orig[paths[i]] = val.toObject({ depopulate: true, _isNested: true });
  63. } else if (val instanceof Date || val[objectIdSymbol]) {
  64. orig[paths[i]] = val;
  65. } else if (typeof val.valueOf === 'function') {
  66. orig[paths[i]] = val.valueOf();
  67. } else {
  68. orig[paths[i]] = val;
  69. }
  70. }
  71. }