common.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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;
  14. if (update && utils.isMongooseObject(update) && !Buffer.isBuffer(update)) {
  15. keys = Object.keys(update.toObject({ transform: false, virtuals: false }));
  16. } else {
  17. keys = Object.keys(update || {});
  18. }
  19. var numKeys = keys.length;
  20. var result = {};
  21. path = path ? path + '.' : '';
  22. for (var i = 0; i < numKeys; ++i) {
  23. var key = keys[i];
  24. var val = update[key];
  25. result[path + key] = val;
  26. if (shouldFlatten(val)) {
  27. if (options && options.skipArrays && Array.isArray(val)) {
  28. continue;
  29. }
  30. var flat = flatten(val, path + key, options);
  31. for (var k in flat) {
  32. result[k] = flat[k];
  33. }
  34. if (Array.isArray(val)) {
  35. result[path + key] = val;
  36. }
  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 (utils.isMongooseObject(val) && !Buffer.isBuffer(val)) {
  54. val = val.toObject({ transform: false, virtuals: false });
  55. }
  56. if (shouldFlatten(val)) {
  57. modifiedPaths(val, path + key, result);
  58. }
  59. }
  60. return result;
  61. }
  62. /*!
  63. * ignore
  64. */
  65. function shouldFlatten(val) {
  66. return val &&
  67. typeof val === 'object' &&
  68. !(val instanceof Date) &&
  69. !(val instanceof ObjectId) &&
  70. (!Array.isArray(val) || val.length > 0) &&
  71. !(val instanceof Buffer);
  72. }