From 3141cb6fa35f4240f67171aceea330474500d1ed Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Wed, 19 Oct 2022 16:29:31 -0400 Subject: [PATCH] fix(document): allow creating document with document array and top-level key named `schema` Fix #12480 --- lib/types/DocumentArray/index.js | 2 +- test/document.test.js | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/lib/types/DocumentArray/index.js b/lib/types/DocumentArray/index.js index 4730a311a1d..4877f1a30ef 100644 --- a/lib/types/DocumentArray/index.js +++ b/lib/types/DocumentArray/index.js @@ -57,7 +57,7 @@ function MongooseDocumentArray(values, path, doc) { // to make more proof against unusual node environments if (doc && doc instanceof Document) { internals[arrayParentSymbol] = doc; - internals[arraySchemaSymbol] = doc.schema.path(path); + internals[arraySchemaSymbol] = doc.$__schema.path(path); // `schema.path()` doesn't drill into nested arrays properly yet, see // gh-6398, gh-6602. This is a workaround because nested arrays are diff --git a/test/document.test.js b/test/document.test.js index 2d38adc8629..df17aa9da77 100644 --- a/test/document.test.js +++ b/test/document.test.js @@ -11928,6 +11928,26 @@ describe('document', function() { assert.ok(rawDoc); assert.deepStrictEqual(rawDoc.tags, ['mongodb']); }); + + it('can create document with document array and top-level key named `schema` (gh-12480)', async function() { + const AuthorSchema = new Schema({ + fullName: { type: 'String', required: true } + }); + + const BookSchema = new Schema({ + schema: { type: 'String', required: true }, + title: { type: 'String', required: true }, + authors: [AuthorSchema] + }, { supressReservedKeysWarning: true }); + + const Book = db.model('Book', BookSchema); + + await Book.create({ + schema: 'design', + authors: [{ fullName: 'Sourabh Bagrecha' }], + title: 'The power of JavaScript' + }); + }); }); describe('Check if instance function that is supplied in schema option is availabe', function() {