MCPcopy Create free account
hub / github.com/Automattic/mongoose / $applyDefaultsToNested

Function $applyDefaultsToNested

lib/document.js:488–547  ·  view source on GitHub ↗
(val, path, doc)

Source from the content-addressed store, hash-verified

486 */
487
488function $applyDefaultsToNested(val, path, doc) {
489 if (val == null) {
490 return;
491 }
492
493 const paths = Object.keys(doc.$__schema.paths);
494 const plen = paths.length;
495
496 const pathPieces = path.indexOf('.') === -1 ? [path] : path.split('.');
497
498 for (let i = 0; i < plen; ++i) {
499 let curPath = '';
500 const p = paths[i];
501
502 if (!p.startsWith(path + '.')) {
503 continue;
504 }
505
506 const type = doc.$__schema.paths[p];
507 const pieces = type.splitPath().slice(pathPieces.length);
508 const len = pieces.length;
509
510 if (type.defaultValue === void 0) {
511 continue;
512 }
513
514 let cur = val;
515
516 for (let j = 0; j < len; ++j) {
517 if (cur == null) {
518 break;
519 }
520
521 const piece = pieces[j];
522
523 if (j === len - 1) {
524 if (cur[piece] !== void 0) {
525 break;
526 }
527
528 try {
529 const def = type.getDefault(doc, false);
530 if (def !== void 0) {
531 cur[piece] = def;
532 }
533 } catch (err) {
534 doc.invalidate(path + '.' + curPath, err);
535 break;
536 }
537
538 break;
539 }
540
541 curPath += (!curPath.length ? '' : '.') + piece;
542
543 cur[piece] = cur[piece] || {};
544 cur = cur[piece];
545 }

Callers 1

document.jsFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected