Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(document): set defaults on subdocuments underneath init-ed single nested subdocument #12523

Merged
merged 3 commits into from Oct 5, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions lib/schema/SubdocumentPath.js
Expand Up @@ -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 {
Expand Down
29 changes: 29 additions & 0 deletions test/document.test.js
Expand Up @@ -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);
vkarpov15 marked this conversation as resolved.
Show resolved Hide resolved
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,
Expand Down