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): correct context for default functions in subdocuments with init #12427

Merged
merged 2 commits into from
Sep 14, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
2 changes: 1 addition & 1 deletion lib/schema/SubdocumentPath.js
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ SubdocumentPath.prototype.cast = function(val, doc, init, priorVal, options) {
}, null);
options = Object.assign({}, options, { priorDoc: priorVal });
if (init) {
subdoc = new Constructor(void 0, selected, doc);
subdoc = new Constructor(void 0, selected, doc, false, { defaults: false });
subdoc.$init(val);
} else {
if (Object.keys(val).length === 0) {
Expand Down
22 changes: 22 additions & 0 deletions test/document.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -11833,6 +11833,28 @@ describe('document', function() {

assert.ok(doc.nestedPath1.mapOfSchema);
});

it('correct context for default functions in subdocuments with init (gh-12328)', async function() {
const subSchema = new mongoose.Schema({
propertyA: { type: String },
propertyB: { type: String, default: function() {
return this.propertyA;
} }
});

const testSchema = new mongoose.Schema(
{
name: String,
sub: { type: subSchema, default: () => ({}) }
}
);

const Test = db.model('Test', testSchema);

await Test.collection.insertOne({ name: 'test', sub: { propertyA: 'foo' } });
const doc = await Test.findOne({ name: 'test' });
assert.strictEqual(doc.sub.propertyB, 'foo');
});
});

describe('Check if instance function that is supplied in schema option is availabe', function() {
Expand Down