Skip to content

Commit

Permalink
fix(document): make array getters avoid unintentionally modifying arr…
Browse files Browse the repository at this point in the history
…ay, defer getters until index access instead

Fix #13748
  • Loading branch information
vkarpov15 committed Aug 23, 2023
1 parent 743c556 commit bebdc09
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 7 deletions.
8 changes: 8 additions & 0 deletions lib/document.js
Original file line number Diff line number Diff line change
Expand Up @@ -4091,6 +4091,14 @@ function applyGetters(self, json, options) {
if (ii === last) {
const val = self.$get(path);
branch[part] = clone(val, options);
if (Array.isArray(branch[part]) && schema.paths[path].$embeddedSchemaType) {
for (let i = 0; i < branch[part].length; ++i) {
branch[part][i] = schema.paths[path].$embeddedSchemaType.applyGetters(
branch[part][i],
self
);
}
}
} else if (v == null) {
if (part in cur) {
branch[part] = v;
Expand Down
7 changes: 0 additions & 7 deletions lib/schema/array.js
Original file line number Diff line number Diff line change
Expand Up @@ -289,13 +289,6 @@ SchemaArray.prototype.applyGetters = function(value, scope) {
}

const ret = SchemaType.prototype.applyGetters.call(this, value, scope);
if (Array.isArray(ret)) {
const rawValue = utils.isMongooseArray(ret) ? ret.__array : ret;
const len = rawValue.length;
for (let i = 0; i < len; ++i) {
rawValue[i] = this.caster.applyGetters(rawValue[i], scope);
}
}
return ret;
};

Expand Down
3 changes: 3 additions & 0 deletions lib/types/array/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,9 @@ function MongooseArray(values, path, doc, schematype) {
if (mongooseArrayMethods.hasOwnProperty(prop)) {
return mongooseArrayMethods[prop];
}
if (typeof prop === 'string' && numberRE.test(prop) && schematype?.$embeddedSchemaType != null) {
return schematype.$embeddedSchemaType.applyGetters(__array[prop], doc);
}

return __array[prop];
},
Expand Down

0 comments on commit bebdc09

Please sign in to comment.