Skip to content

Commit d2a70e3

Browse files
committed
test(discriminator): add test case covering Automattic#15092
1 parent c4fac84 commit d2a70e3

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

test/model.discriminator.test.js

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2317,4 +2317,63 @@ describe('model', function() {
23172317
assert.ok(requestAsReadFromDb.triggeredWorkflows[0].createdAt.valueOf() >= now.valueOf());
23182318
assert.ok(requestAsReadFromDb.triggeredWorkflows[0].updatedAt.valueOf() >= now.valueOf());
23192319
});
2320+
2321+
it('triggers save hooks on subdocuments (gh-15092)', async function() {
2322+
const subdocumentSchema = mongoose.Schema({
2323+
name: String
2324+
});
2325+
2326+
const subdocumentPreSaveHooks = [];
2327+
subdocumentSchema.pre('save', function(next) {
2328+
subdocumentPreSaveHooks.push(this);
2329+
next();
2330+
});
2331+
2332+
const schema = mongoose.Schema({
2333+
name: String,
2334+
subdocuments: [subdocumentSchema]
2335+
}, { discriminatorKey: 'type' });
2336+
2337+
const documentPreSaveHooks = [];
2338+
schema.pre('save', function(next) {
2339+
documentPreSaveHooks.push(this);
2340+
next();
2341+
});
2342+
2343+
const Document = db.model('Document', schema);
2344+
2345+
const discriminatorSchema = mongoose.Schema({});
2346+
2347+
const discriminatorPreSaveHooks = [];
2348+
discriminatorSchema.pre('save', function(next) {
2349+
discriminatorPreSaveHooks.push(this);
2350+
next();
2351+
});
2352+
2353+
const Discriminator = Document.discriminator('Discriminator', discriminatorSchema);
2354+
2355+
const document = new Document({ name: 'Document' });
2356+
document.subdocuments.push({ name: 'Document Subdocument' });
2357+
await document.save();
2358+
2359+
assert.equal(discriminatorPreSaveHooks.length, 0);
2360+
assert.equal(subdocumentPreSaveHooks.length, 1);
2361+
assert.equal(subdocumentPreSaveHooks[0], document.subdocuments[0]);
2362+
assert.equal(documentPreSaveHooks.length, 1);
2363+
assert.equal(documentPreSaveHooks[0], document);
2364+
2365+
subdocumentPreSaveHooks.length = 0;
2366+
documentPreSaveHooks.length = 0;
2367+
2368+
const discriminator = new Discriminator({ name: 'Discriminator', type: 'Discriminator' });
2369+
discriminator.subdocuments.push({ name: 'Discriminator Subdocument' });
2370+
await discriminator.save();
2371+
2372+
assert.equal(subdocumentPreSaveHooks.length, 1);
2373+
assert.equal(subdocumentPreSaveHooks[0], discriminator.subdocuments[0]);
2374+
assert.equal(discriminatorPreSaveHooks.length, 1);
2375+
assert.equal(discriminatorPreSaveHooks[0], discriminator);
2376+
assert.equal(documentPreSaveHooks.length, 1);
2377+
assert.equal(documentPreSaveHooks[0], discriminator);
2378+
});
23202379
});

0 commit comments

Comments
 (0)