Skip to content

Commit

Permalink
Merge pull request #13422 from Automattic/vkarpov15/gh-13372
Browse files Browse the repository at this point in the history
fix(array): track correct changes when setting nested array of primitives
  • Loading branch information
vkarpov15 committed May 23, 2023
2 parents 048ec48 + 88cca18 commit d2cfd25
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 2 deletions.
6 changes: 5 additions & 1 deletion lib/schema/array.js
Original file line number Diff line number Diff line change
Expand Up @@ -359,7 +359,11 @@ SchemaArray.prototype.cast = function(value, doc, init, prev, options) {
options = options || emptyOpts;

let rawValue = utils.isMongooseArray(value) ? value.__array : value;
value = MongooseArray(rawValue, options.path || this._arrayPath || this.path, doc, this);
let path = options.path || this.path;
if (options.arrayPathIndex != null) {
path += '.' + options.arrayPathIndex;
}
value = MongooseArray(rawValue, path, doc, this);
rawValue = value.__array;

if (init && doc != null && doc.$__ != null && doc.$populated(this.path)) {
Expand Down
2 changes: 1 addition & 1 deletion test/schema.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2562,7 +2562,7 @@ describe('schema', function() {
});

const casted = schema.path('ids').cast([[]]);
assert.equal(casted[0].$path(), 'ids.$');
assert.equal(casted[0].$path(), 'ids.0');
});

describe('cast option (gh-8407)', function() {
Expand Down
16 changes: 16 additions & 0 deletions test/types.array.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1899,4 +1899,20 @@ describe('types array', function() {

m.Schema.Types.Array.options.castNonArrays = true;
});

it('supports setting nested arrays directly (gh-13372)', function() {
const Test = db.model('Test', new Schema({ intArr: [[Number]] }));

const intArr = [[1, 2], [3, 4]];
const doc = Test.hydrate({ intArr });

doc.intArr[0][0] = 2;
doc.intArr[1][1] = 5;
assert.deepStrictEqual(doc.getChanges(), {
$set: {
'intArr.0.0': 2,
'intArr.1.1': 5
}
});
});
});

0 comments on commit d2cfd25

Please sign in to comment.