Skip to content

Commit

Permalink
fix(document): allow calling push() with different $position argu…
Browse files Browse the repository at this point in the history
…ments

Fix #14244
Re: #4322
  • Loading branch information
vkarpov15 committed Jan 12, 2024
1 parent 2d68983 commit 195b46c
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 16 deletions.
18 changes: 8 additions & 10 deletions lib/types/array/methods/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

const Document = require('../../../document');
const ArraySubdocument = require('../../ArraySubdocument');
const MongooseError = require('../../../error/mongooseError');
const cleanModifiedSubpaths = require('../../../helpers/document/cleanModifiedSubpaths');
const internalToObjectOptions = require('../../../options').internalToObjectOptions;
const mpath = require('mpath');
Expand Down Expand Up @@ -684,22 +683,21 @@ const methods = {

if ((atomics.$push && atomics.$push.$each && atomics.$push.$each.length || 0) !== 0 &&
atomics.$push.$position != atomic.$position) {
throw new MongooseError('Cannot call `Array#push()` multiple times ' +
'with different `$position`');
}
if (atomic.$position != null) {
[].splice.apply(arr, [atomic.$position, 0].concat(values));
ret = arr.length;
} else {
ret = [].push.apply(arr, values);
}

if (atomic.$position != null) {
this._registerAtomic('$set', this);
} else if (atomic.$position != null) {
[].splice.apply(arr, [atomic.$position, 0].concat(values));
ret = this.length;
} else {
ret = [].push.apply(arr, values);
}
} else {
if ((atomics.$push && atomics.$push.$each && atomics.$push.$each.length || 0) !== 0 &&
atomics.$push.$position != null) {
throw new MongooseError('Cannot call `Array#push()` multiple times ' +
'with different `$position`');
}
atomic = values;
ret = [].push.apply(arr, values);
}
Expand Down
13 changes: 7 additions & 6 deletions test/document.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -8232,12 +8232,13 @@ describe('document', function() {
$each: [0],
$position: 0
});
assert.throws(() => {
doc.nums.push({ $each: [5] });
}, /Cannot call.*multiple times/);
assert.throws(() => {
doc.nums.push(5);
}, /Cannot call.*multiple times/);
assert.deepStrictEqual(doc.nums.$__getAtomics(), [['$push', { $each: [0], $position: 0 }]]);

doc.nums.push({ $each: [5] });
assert.deepStrictEqual(doc.nums.$__getAtomics(), [['$set', [0, 1, 2, 3, 4, 5]]]);

doc.nums.push({ $each: [0.5], $position: 1 });
assert.deepStrictEqual(doc.nums.$__getAtomics(), [['$set', [0, 0.5, 1, 2, 3, 4, 5]]]);
});

it('setting a path to a single nested document should update the single nested doc parent (gh-8400)', function() {
Expand Down

0 comments on commit 195b46c

Please sign in to comment.