Skip to content

Commit

Permalink
fix: make recompileSchema() also clear memoized toObject and toJSON d…
Browse files Browse the repository at this point in the history
…efault options
  • Loading branch information
vkarpov15 committed Jun 17, 2024
1 parent a90aa92 commit 4f645ed
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 11 deletions.
2 changes: 2 additions & 0 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -5105,6 +5105,8 @@ Model.recompileSchema = function recompileSchema() {
}
}

delete this.schema._defaultToObjectOptionsMap;

applyEmbeddedDiscriminators(this.schema, new WeakSet(), true);
};

Expand Down
13 changes: 3 additions & 10 deletions test/document.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,15 +100,6 @@ schema.path('date').set(function(v) {
return v;
});

/**
* Method subject to hooks. Simply fires the callback once the hooks are
* executed.
*/

TestDocument.prototype.hooksTest = function(fn) {
fn(null, arguments);
};

const childSchema = new Schema({ counter: Number });

const parentSchema = new Schema({
Expand Down Expand Up @@ -491,6 +482,7 @@ describe('document', function() {

// all done
delete doc.schema.options.toObject;
delete doc.schema._defaultToObjectOptionsMap;
});

it('toObject transform', async function() {
Expand Down Expand Up @@ -994,6 +986,7 @@ describe('document', function() {

// all done
delete doc.schema.options.toJSON;
delete doc.schema._defaultToObjectOptionsMap;
});

it('jsonifying an object', function() {
Expand All @@ -1004,7 +997,7 @@ describe('document', function() {
// parse again
const obj = JSON.parse(json);

assert.equal(obj.test, 'woot');
assert.equal(obj.test, 'woot', JSON.stringify(obj));
assert.equal(obj._id, oidString);
});

Expand Down
8 changes: 7 additions & 1 deletion test/model.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -7445,7 +7445,7 @@ describe('Model', function() {
});

it('supports recompiling model with new schema additions (gh-14296)', function() {
const schema = new mongoose.Schema({ field: String });
const schema = new mongoose.Schema({ field: String }, { toObject: { virtuals: false } });
const TestModel = db.model('Test', schema);
TestModel.schema.virtual('myVirtual').get(function() {
return this.field + ' from myVirtual';
Expand All @@ -7455,6 +7455,12 @@ describe('Model', function() {

TestModel.recompileSchema();
assert.equal(doc.myVirtual, 'Hello from myVirtual');
assert.strictEqual(doc.toObject().myVirtual, undefined);

doc.schema.options.toObject.virtuals = true;
TestModel.recompileSchema();
assert.equal(doc.myVirtual, 'Hello from myVirtual');
assert.equal(doc.toObject().myVirtual, 'Hello from myVirtual');
});

it('supports recompiling model with new discriminators (gh-14444) (gh-14296)', function() {
Expand Down

0 comments on commit 4f645ed

Please sign in to comment.