Skip to content

Commit 5e95252

Browse files
authored
Merge pull request #15720 from Automattic/vkarpov15/gh-15718
fix(schema): avoid throwing error on array of unions
2 parents dcfe39c + 6ca6708 commit 5e95252

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

lib/schema.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1694,6 +1694,10 @@ Schema.prototype.interpretAsType = function(path, obj, options) {
16941694
`\`${name}\` is not a valid type within the array \`${path}\`.` +
16951695
'See https://bit.ly/mongoose-schematypes for a list of valid schema types.');
16961696
}
1697+
1698+
if (name === 'Union' && typeof cast === 'object') {
1699+
cast.parentSchema = this;
1700+
}
16971701
}
16981702

16991703
return new MongooseTypes.Array(path, cast || MongooseTypes.Mixed, obj, options);

test/schema.union.test.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,4 +134,28 @@ describe('Union', function() {
134134
const doc2FromDb = await TestModel.collection.findOne({ _id: doc2._id });
135135
assert.strictEqual(doc2FromDb.test, 'bbb');
136136
});
137+
138+
it('handles arrays of unions (gh-15718)', async function() {
139+
const schema = new Schema({
140+
arr: [{
141+
type: 'Union',
142+
of: [Number, Date]
143+
}]
144+
});
145+
const TestModel = db.model('Test', schema);
146+
147+
const numValue = 42;
148+
const dateValue = new Date('2025-06-01');
149+
150+
const doc = new TestModel({
151+
arr: [numValue, dateValue]
152+
});
153+
154+
await doc.save();
155+
156+
const found = await TestModel.collection.findOne({ _id: doc._id });
157+
assert.strictEqual(found.arr.length, 2);
158+
assert.strictEqual(found.arr[0], numValue);
159+
assert.strictEqual(new Date(found.arr[1]).valueOf(), dateValue.valueOf());
160+
});
137161
});

0 commit comments

Comments
 (0)