applyDefaultsToPOJO.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. 'use strict';
  2. module.exports = function applyDefaultsToPOJO(doc, schema) {
  3. const paths = Object.keys(schema.paths);
  4. const plen = paths.length;
  5. for (let i = 0; i < plen; ++i) {
  6. let curPath = '';
  7. const p = paths[i];
  8. const type = schema.paths[p];
  9. const path = type.splitPath();
  10. const len = path.length;
  11. let doc_ = doc;
  12. for (let j = 0; j < len; ++j) {
  13. if (doc_ == null) {
  14. break;
  15. }
  16. const piece = path[j];
  17. curPath += (!curPath.length ? '' : '.') + piece;
  18. if (j === len - 1) {
  19. if (typeof doc_[piece] !== 'undefined') {
  20. if (type.$isSingleNested) {
  21. applyDefaultsToPOJO(doc_[piece], type.schema);
  22. } else if (type.$isMongooseDocumentArray && Array.isArray(doc_[piece])) {
  23. doc_[piece].forEach(el => applyDefaultsToPOJO(el, type.schema));
  24. }
  25. break;
  26. }
  27. const def = type.getDefault(doc, false, { skipCast: true });
  28. if (typeof def !== 'undefined') {
  29. doc_[piece] = def;
  30. if (type.$isSingleNested) {
  31. applyDefaultsToPOJO(def, type.schema);
  32. } else if (type.$isMongooseDocumentArray && Array.isArray(def)) {
  33. def.forEach(el => applyDefaultsToPOJO(el, type.schema));
  34. }
  35. }
  36. } else {
  37. if (doc_[piece] == null) {
  38. doc_[piece] = {};
  39. }
  40. doc_ = doc_[piece];
  41. }
  42. }
  43. }
  44. };