From 25e45803e429d7466edf9f7539868c616c4f3042 Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Tue, 2 Aug 2022 21:57:33 -0400 Subject: [PATCH] fix(schema+timestamps): handle `insertMany()` with timestamps and discriminators Fix #12150 --- lib/schema/SubdocumentPath.js | 1 + lib/schema/documentarray.js | 1 + test/timestamps.test.js | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 37 insertions(+) diff --git a/lib/schema/SubdocumentPath.js b/lib/schema/SubdocumentPath.js index 6c4ed32f8b7..0605b9ab90e 100644 --- a/lib/schema/SubdocumentPath.js +++ b/lib/schema/SubdocumentPath.js @@ -47,6 +47,7 @@ function SubdocumentPath(schema, path, options) { this.caster.prototype.$basePath = path; this.schema = schema; this.$isSingleNested = true; + this.base = schema.base; SchemaType.call(this, path, options, 'Embedded'); } diff --git a/lib/schema/documentarray.js b/lib/schema/documentarray.js index 77c3c409d63..0c552453fbc 100644 --- a/lib/schema/documentarray.js +++ b/lib/schema/documentarray.js @@ -147,6 +147,7 @@ function _createConstructor(schema, options, baseClass) { EmbeddedDocument.prototype.constructor = EmbeddedDocument; EmbeddedDocument.$isArraySubdocument = true; EmbeddedDocument.events = new EventEmitter(); + EmbeddedDocument.base = schema.base; // apply methods for (const i in schema.methods) { diff --git a/test/timestamps.test.js b/test/timestamps.test.js index fdb60a0707e..9df75016fdc 100644 --- a/test/timestamps.test.js +++ b/test/timestamps.test.js @@ -995,6 +995,41 @@ describe('timestamps', function() { assert.ok(res.profile.conditions[0].createdAt); assert.ok(res.profile.conditions[0].updatedAt); }); + + it('works with insertMany() and embedded discriminators (gh-12150)', async function() { + const AssetSchema = new Schema({ url: String, size: String }, { timestamps: true }); + const HeaderSectionSchema = new Schema({ + title: String, + image: AssetSchema + }); + + // Abstract section + const BaseSectionSchema = new Schema({ + isVisible: Boolean + }, { discriminatorKey: 'kind' }); + + // Main Schema + const PageSchema = new Schema({ + sections: [BaseSectionSchema] // Same error without the array "sections: BaseSectionSchema" + }, { timestamps: true }); + + const sections = PageSchema.path('sections'); + sections.discriminator('header', HeaderSectionSchema); + + const Test = db.model('Test', PageSchema); + + await Test.insertMany([{ + sections: { + isVisible: true, + kind: 'header', + title: 'h1' + } + }]); + + const doc = await Test.findOne(); + assert.equal(doc.sections.length, 1); + assert.equal(doc.sections[0].title, 'h1'); + }); }); async function delay(ms) {