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.

83 lines
1.6 KiB

  1. 'use strict';
  2. /*!
  3. * Module dependencies.
  4. */
  5. var ObjectId = require('../types/objectid');
  6. var utils = require('../utils');
  7. exports.flatten = flatten;
  8. exports.modifiedPaths = modifiedPaths;
  9. /*!
  10. * ignore
  11. */
  12. function flatten(update, path, options) {
  13. var keys = Object.keys(update || {});
  14. var numKeys = keys.length;
  15. var result = {};
  16. path = path ? path + '.' : '';
  17. for (var i = 0; i < numKeys; ++i) {
  18. var key = keys[i];
  19. var val = update[key];
  20. if (utils.isMongooseObject(val) && !Buffer.isBuffer(val)) {
  21. val = val.toObject({ virtuals: false });
  22. }
  23. if (shouldFlatten(val)) {
  24. result[path + key] = val;
  25. if (options && options.skipArrays && Array.isArray(val)) {
  26. continue;
  27. }
  28. var flat = flatten(val, path + key);
  29. for (var k in flat) {
  30. result[k] = flat[k];
  31. }
  32. if (Array.isArray(val)) {
  33. result[path + key] = val;
  34. }
  35. } else {
  36. result[path + key] = val;
  37. }
  38. }
  39. return result;
  40. }
  41. /*!
  42. * ignore
  43. */
  44. function modifiedPaths(update, path, result) {
  45. var keys = Object.keys(update || {});
  46. var numKeys = keys.length;
  47. result = result || {};
  48. path = path ? path + '.' : '';
  49. for (var i = 0; i < numKeys; ++i) {
  50. var key = keys[i];
  51. var val = update[key];
  52. result[path + key] = true;
  53. if (shouldFlatten(val)) {
  54. modifiedPaths(val, path + key, result);
  55. }
  56. }
  57. return result;
  58. }
  59. /*!
  60. * ignore
  61. */
  62. function shouldFlatten(val) {
  63. return val &&
  64. typeof val === 'object' &&
  65. !(val instanceof Date) &&
  66. !(val instanceof ObjectId) &&
  67. (!Array.isArray(val) || val.length > 0) &&
  68. !(val instanceof Buffer);
  69. }