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 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
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