Skip to content

Commit

Permalink
fix(document): correct context for default functions in subdocuments …
Browse files Browse the repository at this point in the history
…with init

Fix #12328
  • Loading branch information
vkarpov15 committed Sep 14, 2022
1 parent 01145a2 commit b46848d
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/schema/SubdocumentPath.js
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
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

0 comments on commit b46848d

Please sign in to comment.