diff --git a/lib/schema/SubdocumentPath.js b/lib/schema/SubdocumentPath.js index e748d6a5026..1eb65207d85 100644 --- a/lib/schema/SubdocumentPath.js +++ b/lib/schema/SubdocumentPath.js @@ -172,6 +172,7 @@ SubdocumentPath.prototype.cast = function(val, doc, init, priorVal, options) { options = Object.assign({}, options, { priorDoc: priorVal }); if (init) { subdoc = new Constructor(void 0, selected, doc, false, { defaults: false }); + delete subdoc.$__.defaults; subdoc.$init(val); applyDefaults(subdoc, selected); } else { diff --git a/test/document.test.js b/test/document.test.js index ca2aca278d9..2d38adc8629 100644 --- a/test/document.test.js +++ b/test/document.test.js @@ -11865,6 +11865,35 @@ describe('document', function() { assert.strictEqual(called, 1); }); + it('applies defaults to pushed subdocs after initing document (gh-12515)', async function() { + const animalSchema = new Schema({ title: String }); + const animalsSchema = new Schema({ + species: [animalSchema], + totalAnimals: Number + }); + const Userschema = new Schema({ + animals: animalsSchema + }); + const UserModel = db.model('User', Userschema); + + const doc = new UserModel(); + doc.animals = { totalAnimals: 1 }; + doc.animals.species = [{ title: 'Lion' }]; + await doc.save(); + // once created we fetch it again + let user = await UserModel.findById(doc._id); + + // add new animal + user.animals.species.push({ title: 'Elephant' }); + await user.save(); + assert.ok(user.animals.species[0]._id); + assert.ok(user.animals.species[1]._id); + user = await UserModel.collection.findOne({ _id: user._id }); + + assert.ok(user.animals.species[0]._id); + assert.ok(user.animals.species[1]._id); + }); + it('If the field does not exist, $inc should create it and set is value to the specified one (gh-12435)', async function() { const schema = new mongoose.Schema({ name: String,