Skip to content

Commit

Permalink
Merge pull request #9013 from philippejer/gh-9012
Browse files Browse the repository at this point in the history
fix(documentarray): make sure you can call `unshift()` after `map()`
  • Loading branch information
vkarpov15 committed May 18, 2020
2 parents ed97aac + 1b190b6 commit 14bba6f
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
12 changes: 9 additions & 3 deletions lib/types/core_array.js
Original file line number Diff line number Diff line change
Expand Up @@ -879,7 +879,7 @@ class CoreMongooseArray extends Array {
*
* ####Note:
*
* _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._
* _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwriting any changes that happen between when you retrieved the object and when you save it._
*
* @api public
* @method unshift
Expand All @@ -889,8 +889,14 @@ class CoreMongooseArray extends Array {
unshift() {
_checkManualPopulation(this, arguments);

let values = [].map.call(arguments, this._cast, this);
values = this[arraySchemaSymbol].applySetters(values, this[arrayParentSymbol]);
let values;
if (this[arraySchemaSymbol] == null) {
values = arguments;
} else {
values = [].map.call(arguments, this._cast, this);
values = this[arraySchemaSymbol].applySetters(values, this[arrayParentSymbol]);
}

[].unshift.apply(this, values);
this._registerAtomic('$set', this);
this._markModified();
Expand Down
21 changes: 21 additions & 0 deletions test/types.documentarray.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -611,6 +611,27 @@ describe('types.documentarray', function() {
'd'
]);
});

it('unshift() after map() works (gh-9012)', function() {
const MyModel = db.model('Test', Schema({
myArray: [{ name: String }]
}));

const doc = new MyModel({
myArray: [{ name: 'b' }, { name: 'c' }]
});
let myArray = doc.myArray;

myArray = myArray.map(val => ({ name: `${val.name} mapped` }));

myArray.unshift({ name: 'a inserted' });

assert.deepEqual(myArray.map(v => v.name), [
'a inserted',
'b mapped',
'c mapped'
]);
});
});

it('cleans modified subpaths on splice() (gh-7249)', function() {
Expand Down

0 comments on commit 14bba6f

Please sign in to comment.