From 4a946ffb9a3e37efa46603b60c05a9782cf16e74 Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Tue, 23 Aug 2022 15:13:51 -0400 Subject: [PATCH] fix(schema): make ArraySubdocuments apply `_id` defaults on init Fix #12264 --- lib/schema/documentarray.js | 2 +- test/types.documentarray.test.js | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/lib/schema/documentarray.js b/lib/schema/documentarray.js index 0c552453fbc..0bb64d779cf 100644 --- a/lib/schema/documentarray.js +++ b/lib/schema/documentarray.js @@ -392,7 +392,7 @@ DocumentArrayPath.prototype.getDefault = function(scope, init, options) { }; const _toObjectOptions = Object.freeze({ transform: false, virtuals: false }); -const initDocumentOptions = Object.freeze({ skipId: true, willInit: true }); +const initDocumentOptions = Object.freeze({ skipId: false, willInit: true }); /** * Casts contents diff --git a/test/types.documentarray.test.js b/test/types.documentarray.test.js index 6ee188f9eb4..c5b0c5221c8 100644 --- a/test/types.documentarray.test.js +++ b/test/types.documentarray.test.js @@ -748,4 +748,18 @@ describe('types.documentarray', function() { doc.arr.push(subdoc); await doc.validate(); }); + + it('applies _id default (gh-12264)', function() { + mongoose.deleteModel(/Test/); + const nestedArraySchema = Schema({ + subDocArray: [{ name: String }] + }); + + const Model = db.model('Test', nestedArraySchema); + const doc = new Model().init({ + subDocArray: [{ name: 'foo' }] + }); + + assert.ok(doc.subDocArray[0]._id instanceof mongoose.Types.ObjectId); + }); });