Skip to content

Commit

Permalink
fix(document): skip casting when initing a populated path
Browse files Browse the repository at this point in the history
Fix #8062
  • Loading branch information
vkarpov15 committed Aug 17, 2019
1 parent 5f416bf commit aa5e737
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 5 deletions.
10 changes: 6 additions & 4 deletions lib/document.js
Original file line number Diff line number Diff line change
Expand Up @@ -482,11 +482,12 @@ Document.prototype.init = function(doc, opts, fn) {
Document.prototype.$__init = function(doc, opts) {
this.isNew = false;
this.$init = true;
opts = opts || {};

// handle docs with populated paths
// If doc._id is not null or undefined
if (doc._id !== null && doc._id !== undefined &&
opts && opts.populated && opts.populated.length) {
opts.populated && opts.populated.length) {
const id = String(doc._id);
for (let i = 0; i < opts.populated.length; ++i) {
const item = opts.populated[i];
Expand All @@ -498,7 +499,7 @@ Document.prototype.$__init = function(doc, opts) {
}
}

init(this, doc, this._doc);
init(this, doc, this._doc, opts);

this.emit('init', this);
this.constructor.emit('init', this);
Expand All @@ -517,7 +518,7 @@ Document.prototype.$__init = function(doc, opts) {
* @api private
*/

function init(self, obj, doc, prefix) {
function init(self, obj, doc, opts, prefix) {
prefix = prefix || '';

const keys = Object.keys(obj);
Expand Down Expand Up @@ -548,7 +549,7 @@ function init(self, obj, doc, prefix) {
if (!doc[i]) {
doc[i] = {};
}
init(self, obj[i], doc[i], path + '.');
init(self, obj[i], doc[i], opts, path + '.');
} else if (!schema) {
doc[i] = obj[i];
} else {
Expand All @@ -557,6 +558,7 @@ function init(self, obj, doc, prefix) {
} else if (obj[i] !== undefined) {
const intCache = obj[i].$__ || {};
const wasPopulated = intCache.wasPopulated || null;

if (schema && !wasPopulated) {
try {
doc[i] = schema.cast(obj[i], self, true);
Expand Down
2 changes: 1 addition & 1 deletion lib/schema/array.js
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ SchemaArray.prototype.cast = function(value, doc, init) {
value = new MongooseArray(value, this.path, doc);
}

if (this.caster && this.casterConstructor !== Mixed) {
if (this.caster && this.casterConstructor !== Mixed && doc != null && doc.$__ != null && !doc.populated(this.path)) {
try {
for (i = 0, l = value.length; i < l; i++) {
value[i] = this.caster.cast(value[i], doc, init);
Expand Down

0 comments on commit aa5e737

Please sign in to comment.