diff --git a/lib/document.js b/lib/document.js index fe636a4c351..757f5101c32 100644 --- a/lib/document.js +++ b/lib/document.js @@ -741,7 +741,7 @@ function init(self, obj, doc, opts, prefix) { if (i === '__proto__' || i === 'constructor') { return; } - path = prefix + i; + path = prefix ? prefix + i : i; schemaType = docSchema.path(path); // Should still work if not a model-level discriminator, but should not be @@ -751,7 +751,8 @@ function init(self, obj, doc, opts, prefix) { return; } - if (!schemaType && utils.isPOJO(obj[i])) { + const value = obj[i]; + if (!schemaType && utils.isPOJO(value)) { // assume nested object if (!doc[i]) { doc[i] = {}; @@ -759,30 +760,30 @@ function init(self, obj, doc, opts, prefix) { self[i] = doc[i]; } } - init(self, obj[i], doc[i], opts, path + '.'); + init(self, value, doc[i], opts, path + '.'); } else if (!schemaType) { - doc[i] = obj[i]; + doc[i] = value; if (!strict && !prefix) { - self[i] = obj[i]; + self[i] = value; } } else { // Retain order when overwriting defaults - if (doc.hasOwnProperty(i) && obj[i] !== void 0) { + if (doc.hasOwnProperty(i) && value !== void 0) { delete doc[i]; } - if (obj[i] === null) { + if (value === null) { doc[i] = schemaType._castNullish(null); - } else if (obj[i] !== undefined) { - const wasPopulated = obj[i].$__ == null ? null : obj[i].$__.wasPopulated; + } else if (value !== undefined) { + const wasPopulated = value.$__ == null ? null : value.$__.wasPopulated; if (schemaType && !wasPopulated) { try { if (opts && opts.setters) { // Call applySetters with `init = false` because otherwise setters are a noop const overrideInit = false; - doc[i] = schemaType.applySetters(obj[i], self, overrideInit); + doc[i] = schemaType.applySetters(value, self, overrideInit); } else { - doc[i] = schemaType.cast(obj[i], self, true); + doc[i] = schemaType.cast(value, self, true); } } catch (e) { self.invalidate(e.path, new ValidatorError({ @@ -794,7 +795,7 @@ function init(self, obj, doc, opts, prefix) { })); } } else { - doc[i] = obj[i]; + doc[i] = value; } } // mark as hydrated diff --git a/lib/schema.js b/lib/schema.js index 88e427d417d..dc0ebbd5003 100644 --- a/lib/schema.js +++ b/lib/schema.js @@ -955,6 +955,9 @@ reserved.collection = 1; Schema.prototype.path = function(path, obj) { if (obj === undefined) { + if (this.paths[path] != null) { + return this.paths[path]; + } // Convert to '.$' to check subpaths re: gh-6405 const cleanPath = _pathToPositionalSyntax(path); let schematype = _getPath(this, path, cleanPath);