common.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. 'use strict';
  2. /*!
  3. * Module dependencies.
  4. */
  5. const Binary = require('../driver').get().Binary;
  6. const isBsonType = require('./isBsonType');
  7. const isMongooseObject = require('./isMongooseObject');
  8. exports.flatten = flatten;
  9. exports.modifiedPaths = modifiedPaths;
  10. /*!
  11. * ignore
  12. */
  13. function flatten(update, path, options, schema) {
  14. let keys;
  15. if (update && isMongooseObject(update) && !Buffer.isBuffer(update)) {
  16. keys = Object.keys(update.toObject({ transform: false, virtuals: false }) || {});
  17. } else {
  18. keys = Object.keys(update || {});
  19. }
  20. const numKeys = keys.length;
  21. const result = {};
  22. path = path ? path + '.' : '';
  23. for (let i = 0; i < numKeys; ++i) {
  24. const key = keys[i];
  25. const val = update[key];
  26. result[path + key] = val;
  27. // Avoid going into mixed paths if schema is specified
  28. const keySchema = schema && schema.path && schema.path(path + key);
  29. const isNested = schema && schema.nested && schema.nested[path + key];
  30. if (keySchema && keySchema.instance === 'Mixed') continue;
  31. if (shouldFlatten(val)) {
  32. if (options && options.skipArrays && Array.isArray(val)) {
  33. continue;
  34. }
  35. const flat = flatten(val, path + key, options, schema);
  36. for (const k in flat) {
  37. result[k] = flat[k];
  38. }
  39. if (Array.isArray(val)) {
  40. result[path + key] = val;
  41. }
  42. }
  43. if (isNested) {
  44. const paths = Object.keys(schema.paths);
  45. for (const p of paths) {
  46. if (p.startsWith(path + key + '.') && !result.hasOwnProperty(p)) {
  47. result[p] = void 0;
  48. }
  49. }
  50. }
  51. }
  52. return result;
  53. }
  54. /*!
  55. * ignore
  56. */
  57. function modifiedPaths(update, path, result) {
  58. const keys = Object.keys(update || {});
  59. const numKeys = keys.length;
  60. result = result || {};
  61. path = path ? path + '.' : '';
  62. for (let i = 0; i < numKeys; ++i) {
  63. const key = keys[i];
  64. let val = update[key];
  65. const _path = path + key;
  66. result[_path] = true;
  67. if (!Buffer.isBuffer(val) && isMongooseObject(val)) {
  68. val = val.toObject({ transform: false, virtuals: false });
  69. }
  70. if (shouldFlatten(val)) {
  71. modifiedPaths(val, path + key, result);
  72. }
  73. }
  74. return result;
  75. }
  76. /*!
  77. * ignore
  78. */
  79. function shouldFlatten(val) {
  80. return val &&
  81. typeof val === 'object' &&
  82. !(val instanceof Date) &&
  83. !isBsonType(val, 'ObjectID') &&
  84. (!Array.isArray(val) || val.length !== 0) &&
  85. !(val instanceof Buffer) &&
  86. !isBsonType(val, 'Decimal128') &&
  87. !(val instanceof Binary);
  88. }