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

feat(model): add recompileSchema() function to models to allow applying schema changes after compiling #14306

Merged
merged 6 commits into from Feb 6, 2024
28 changes: 28 additions & 0 deletions lib/model.js
Expand Up @@ -4861,6 +4861,34 @@ Model.__subclass = function subclass(conn, schema, collection) {
return Model;
};

/**
* Apply changes made to this model's schema after this model was compiled.
* By default, adding virtuals and other properties to a schema after the model is compiled does nothing.
* Call this function to apply virtuals and properties that were added later.
*
* #### Example:
* const schema = new mongoose.Schema({ field: String });
vkarpov15 marked this conversation as resolved.
Show resolved Hide resolved
* const TestModel = mongoose.model('Test', schema);
* TestModel.schema.virtual('myVirtual').get(function() {
* return this.field + ' from myVirtual';
* });
* const doc = new TestModel({ field: 'Hello' });
* doc.myVirtual; // undefined
*
* TestModel.recompileSchema();
* doc.myVirtual; // 'Hello from myVirtual'
*
* @return {Model}
vkarpov15 marked this conversation as resolved.
Show resolved Hide resolved
* @api public
* @memberOf Model
* @static
* @method recompileSchema
*/

Model.recompileSchema = function recompileSchema() {
this.prototype.$__setSchema(this.schema);
};

/**
* Helper for console.log. Given a model named 'MyModel', returns the string
* `'Model { MyModel }'`.
Expand Down
13 changes: 13 additions & 0 deletions test/model.test.js
Expand Up @@ -7302,6 +7302,19 @@ describe('Model', function() {
/First argument to `Model` constructor must be an object/
);
});

vkarpov15 marked this conversation as resolved.
Show resolved Hide resolved
it('supports recompiling model with new schema additions (gh-14296)', function() {
const schema = new mongoose.Schema({ field: String });
const TestModel = db.model('Test', schema);
TestModel.schema.virtual('myVirtual').get(function() {
return this.field + ' from myVirtual';
});
const doc = new TestModel({ field: 'Hello' });
assert.strictEqual(doc.myVirtual, undefined);

TestModel.recompileSchema();
assert.equal(doc.myVirtual, 'Hello from myVirtual');
});
});


Expand Down