Skip to content

Commit 2d6bbf9

Browse files
committed
fix(model): add version to save() filter if pushing to a nested array
Fix #11108
1 parent 0bc5489 commit 2d6bbf9

File tree

2 files changed

+24
-5
lines changed

2 files changed

+24
-5
lines changed

lib/model.js

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -589,18 +589,18 @@ function operand(self, where, delta, data, val, op) {
589589
// editing the correct array element.
590590
// only increment the version if an array position changes.
591591
// modifying elements of an array is ok if position does not change.
592-
if (op === '$push' || op === '$addToSet' || op === '$pullAll' || op === '$pull') {
592+
if (/\.\d+\.|\.\d+$/.test(data.path)) {
593+
// now handling $set, $unset
594+
// subpath of array
595+
self.$__.version = VERSION_WHERE;
596+
} else if (op === '$push' || op === '$addToSet' || op === '$pullAll' || op === '$pull') {
593597
self.$__.version = VERSION_INC;
594598
} else if (/^\$p/.test(op)) {
595599
// potentially changing array positions
596600
increment.call(self);
597601
} else if (Array.isArray(val)) {
598602
// $set an array
599603
increment.call(self);
600-
} else if (/\.\d+\.|\.\d+$/.test(data.path)) {
601-
// now handling $set, $unset
602-
// subpath of array
603-
self.$__.version = VERSION_WHERE;
604604
}
605605
}
606606

test/versioning.test.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -651,4 +651,23 @@ describe('versioning', function() {
651651
assert.ok(err);
652652
assert.equal(err.name, 'VersionError');
653653
});
654+
655+
it('adds version to filter if pushing to a nested array (gh-11108)', async function() {
656+
const Test = db.model('Test', Schema({ comments: [{ likedBy: [String] }] }));
657+
const entry = await Test.create({
658+
comments: [{ likedBy: ['Friends', 'Family'] }]
659+
});
660+
661+
const post1 = await Test.findById(entry._id).exec();
662+
const post2 = await Test.findById(entry._id).exec();
663+
664+
post1.comments = [{ likedBy: ['test'] }];
665+
await post1.save();
666+
667+
const comment = post2.comments[0];
668+
comment.likedBy.push('Some User');
669+
670+
const err = await post2.save().then(() => null, err => err);
671+
assert.equal(err.name, 'VersionError');
672+
});
654673
});

0 commit comments

Comments
 (0)