Skip to content

Commit 9a93968

Browse files
authored
Merge pull request #15964 from Automattic/vkarpov15/gh-15956
fix(model): make hydrate() handle nested schema arrays
2 parents 522fb8a + 5a84e48 commit 9a93968

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

lib/schema/array.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -398,6 +398,9 @@ SchemaArray.prototype.cast = function(value, doc, init, prev, options) {
398398
if (options.hydratedPopulatedDocs) {
399399
opts.hydratedPopulatedDocs = options.hydratedPopulatedDocs;
400400
}
401+
if (options.virtuals) {
402+
opts.virtuals = options.virtuals;
403+
}
401404
rawValue[i] = caster.applySetters(rawValue[i], doc, init, void 0, opts);
402405
}
403406
} catch (e) {

test/model.hydrate.test.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -318,5 +318,43 @@ describe('model', function() {
318318

319319
assert.ok(!hydrated.stories[1].article);
320320
});
321+
322+
it('applies virtuals to doubly-nested arrays (gh-15956)', function() {
323+
const innerSchema = new Schema({ name: String });
324+
innerSchema.virtual('computed');
325+
326+
const schema = new Schema({
327+
matrix: [[innerSchema]]
328+
});
329+
330+
const Model = db.model('Test3', schema);
331+
332+
const raw = {
333+
_id: new mongoose.Types.ObjectId(),
334+
matrix: [
335+
[
336+
{ name: 'a', computed: 'virtual-a' },
337+
{ name: 'b', computed: 'virtual-b' }
338+
],
339+
[
340+
{ name: 'c', computed: 'virtual-c' }
341+
]
342+
]
343+
};
344+
345+
const doc = Model.hydrate(raw, null, { virtuals: true });
346+
347+
assert.strictEqual(doc.matrix[0][0].name, 'a');
348+
assert.strictEqual(doc.matrix[0][0].computed, 'virtual-a');
349+
assert.strictEqual(doc.matrix[0][1].name, 'b');
350+
assert.strictEqual(doc.matrix[0][1].computed, 'virtual-b');
351+
assert.strictEqual(doc.matrix[1][0].name, 'c');
352+
assert.strictEqual(doc.matrix[1][0].computed, 'virtual-c');
353+
354+
// Test without virtuals option - should not apply virtuals
355+
const doc2 = Model.hydrate(raw, null);
356+
assert.strictEqual(doc2.matrix[0][0].name, 'a');
357+
assert.strictEqual(doc2.matrix[0][0].computed, undefined);
358+
});
321359
});
322360
});

0 commit comments

Comments
 (0)