Skip to content

Commit

Permalink
Merge pull request #12427 from Automattic/vkarpov15/gh-12328
Browse files Browse the repository at this point in the history
fix(document): correct context for default functions in subdocuments with init
  • Loading branch information
vkarpov15 committed Sep 14, 2022
2 parents 01145a2 + 47ce125 commit 5f62e70
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/schema/SubdocumentPath.js
Expand Up @@ -9,6 +9,7 @@ const EventEmitter = require('events').EventEmitter;
const ObjectExpectedError = require('../error/objectExpected');
const SchemaSubdocumentOptions = require('../options/SchemaSubdocumentOptions');
const SchemaType = require('../schematype');
const applyDefaults = require('../helpers/document/applyDefaults');
const $exists = require('./operators/exists');
const castToNumber = require('./operators/helpers').castToNumber;
const discriminator = require('../helpers/model/discriminator');
Expand Down Expand Up @@ -170,8 +171,9 @@ 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);
applyDefaults(subdoc, selected);
} else {
if (Object.keys(val).length === 0) {
return new Constructor({}, selected, doc, undefined, options);
Expand Down
31 changes: 31 additions & 0 deletions test/document.test.js
Expand Up @@ -11833,6 +11833,37 @@ describe('document', function() {

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

it('correct context for default functions in subdocuments with init (gh-12328)', async function() {
let called = 0;

const subSchema = new mongoose.Schema({
propertyA: { type: String },
propertyB: {
type: String,
default: function() {
++called;
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' } });
assert.strictEqual(called, 0);

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

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

0 comments on commit 5f62e70

Please sign in to comment.