Skip to content

Commit

Permalink
fix(array): make sure Array#toObject() returns a vanilla JavaScript…
Browse files Browse the repository at this point in the history
… array in Node.js 6+

Fix #9540
  • Loading branch information
vkarpov15 committed Nov 13, 2020
1 parent 3d9c4e6 commit cc70256
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
6 changes: 4 additions & 2 deletions lib/types/core_array.js
Original file line number Diff line number Diff line change
Expand Up @@ -869,14 +869,16 @@ class CoreMongooseArray extends Array {
if (options && options.depopulate) {
options = utils.clone(options);
options._isNested = true;
return this.map(function(doc) {
// Ensure return value is a vanilla array, because in Node.js 6+ `map()`
// is smart enough to use the inherited array's constructor.
return [].concat(this).map(function(doc) {
return doc instanceof Document
? doc.toObject(options)
: doc;
});
}

return this.slice();
return [].concat(this);
}

/**
Expand Down
21 changes: 19 additions & 2 deletions test/types.array.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -379,12 +379,12 @@ describe('types array', function() {
const removed = doc.numbers.splice(1, 1, '10');
assert.deepEqual(removed, [5]);
assert.equal(typeof doc.numbers[1], 'number');
assert.deepEqual(doc.numbers.toObject(), [4, 10, 6, 7]);
assert.deepStrictEqual(doc.numbers.toObject(), [4, 10, 6, 7]);
doc.save(function(err) {
assert.ifError(err);
A.findById(a._id, function(err, doc) {
assert.ifError(err);
assert.deepEqual(doc.numbers.toObject(), [4, 10, 6, 7]);
assert.deepStrictEqual(doc.numbers.toObject(), [4, 10, 6, 7]);

A.collection.drop(function(err) {
assert.ifError(err);
Expand Down Expand Up @@ -1828,6 +1828,23 @@ describe('types array', function() {
});
});

it('toObject returns a vanilla JavaScript array (gh-9540)', function() {
const schema = new Schema({ arr: [Number] });
const M = db.model('Test', schema);

const doc = new M({ arr: [1, 2, 3] });

let arr = doc.arr.toObject();
assert.ok(Array.isArray(arr));
assert.equal(arr.constructor, Array);
assert.deepStrictEqual(arr, [1, 2, 3]);

arr = doc.arr.toObject({ depopulate: true });
assert.ok(Array.isArray(arr));
assert.equal(arr.constructor, Array);
assert.deepStrictEqual(arr, [1, 2, 3]);
});

it('pushing top level arrays and subarrays works (gh-1073)', function(done) {
const schema = new Schema({ em: [new Schema({ sub: [String] })] });
const M = db.model('Test', schema);
Expand Down

0 comments on commit cc70256

Please sign in to comment.